﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SYcwpb.Helpers;
using System.Data;
using System.Collections;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using SYcwpb.ViewModels;


namespace SYcwpb.Views
{
    /// <summary>
    /// DriverCombineView.xaml 的交互逻辑
    /// </summary>
    public partial class DriverCombineView : Window
    {
        private static DriverCombineView _view = null;

        private const string isQuitUser = " and (quit is null or LTRIM(quit)='') ";

        private int rowCount = 16;
        private ShowTip tip;
        public static int lineid = Convert.ToInt32(CONSTDATA.UserModel.Line);
        private SqlDataLayer sqlHelper = new SqlDataLayer();
        private ExcelHelper excelHelper = null;
        private ObservableCollection<string> IndexList = new ObservableCollection<string>();
        private ObservableCollection<string> DriverList = new ObservableCollection<string>();
        private ObservableCollection<string> MonDriverList = new ObservableCollection<string>();
        private ObservableCollection<string> MonDriverTwoList = new ObservableCollection<string>();
        private ObservableCollection<string> MonDriverThreeList = new ObservableCollection<string>();

        private Dictionary<int, Driver> DicDriverInfo = new Dictionary<int, Driver>();
        private Dictionary<int, bool> CheckIndexSingle;

        private DriverGroupCombine[,] panelArr;

        /// <summary>
        /// 热备、调车、试车线、备用、正常、月备用
        /// </summary>
        public static Dictionary<string, int> Group = new Dictionary<string, int>();

        int teamID = -1;

        /// <summary>
        ///  -1 无操作
        ///  0  修改
        ///  1  添加
        ///  2  删除
        /// </summary>
        private int Action = -1;

        /// <summary>
        /// 电客车分队集合
        /// </summary>
        private List<DataRow[]> TeamList;

        public static DriverCombineView GetInstance()
        {
            if (null == _view || WindowHelper.IsDisposed(_view))
                _view = new DriverCombineView();
            return _view;
        }

        private DriverCombineView()
        {
            try
            {
                InitializeComponent();

                InitNotes();

                InitGroup();

                InitDriverComboBox();

                InitTeamList();

                InitDriverGroupList();

                InitDate();

                cob_Index.ItemsSource = IndexList;

                cbbdriver.ItemsSource = DicDriverInfo.Values;
                cbbdriver.SelectedValuePath = "userViewName";
                cbbdriver.DisplayMemberPath = "userViewNameAndUserName";
            }
            catch (System.Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }

        }
        private void SelDriverByListView(object sender, RoutedEventArgs e)
        {
            try
            {
                if (cbbdriver.SelectedValue == null)
                    return;
                string driverName = cbbdriver.SelectedValue.ToString();
                for (int y = 0; y < TeamList.Count; y++)
                {
                    for (int x = 0; x < TeamList[y].Length; x++)
                    {
                        if(driverName== panelArr[y, x].OperateDriver)
                        {
                            panelArr[y, x].setHighlight(0);
                            return;
                        }else if (driverName == panelArr[y, x].MonitorDriver)
                        {
                            panelArr[y, x].setHighlight(1);
                            return;
                        }
                        else if (driverName == panelArr[y, x].MonitorDriverTwo)
                        {
                            panelArr[y, x].setHighlight(2);
                            return;
                        }
                        else if (driverName == panelArr[y, x].MonitorDriverThree)
                        {
                            panelArr[y, x].setHighlight(3);
                            return;
                        }
                    }
                }
                MessageBox.Show(driverName+"司机没有在班组内");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void InitNotes()
        {
            string sql_get = "select cfg_value from ConfigSetting where cfg_view = 'DriverCombineView' and cfg_key = 'Notes'";
            string content = Convert.ToString(sqlHelper.GetSingle(sql_get));

            rtb_note.Document = new FlowDocument(new Paragraph(new Run(content)));
        }

        private void IS_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            this.cob_opDriver.Text = "";
            this.cob_moniDriver.Text = "";
            this.cob_moniDriverTwo.Text = "";
            switch (cb.Name)
            {
                case "cb_modify":
                    this.cb_add.IsChecked = false;
                    this.cb_delete.IsChecked = false;
                    this.cb_addDriver.IsChecked = false;
                    Action = 0;
                    InitDriverComboBox();
                    break;
                case "cb_add":
                    this.cb_modify.IsChecked = false;
                    this.cb_delete.IsChecked = false;
                    this.cb_addDriver.IsChecked = false;
                    Action = 1;
                    InitDriverComBoxByAdd();
                    break;
                case "cb_delete":
                    this.cb_modify.IsChecked = false;
                    this.cb_add.IsChecked = false;
                    this.cb_addDriver.IsChecked = false;
                    Action = 2;
                    //InitDriverComboBox();
                    InitDriverComboBoxDel();
                    break;
                case "cb_addDriver":
                    this.cb_modify.IsChecked = false;
                    this.cb_add.IsChecked = false;
                    this.cb_delete.IsChecked = false;
                    Action = 3;
                    InitDriverComboBoxAddDriver();
                    break;
            }
            if (teamID != -1)
            {
                ReInitIndexList(teamID);
            }
            if (Action != 3)
            {
                EnableDrivers();
            }
        }
        private void EnableDrivers() {
            this.cob_opDriver.IsEnabled = true;
            this.cob_moniDriver.IsEnabled = true;
            this.cob_moniDriverTwo.IsEnabled = true;
            this.cob_moniDriverThree.IsEnabled = true;
        }
        private void Not_Checked(object sender, RoutedEventArgs e)
        {
            if (cb_add.IsChecked == false && cb_modify.IsChecked == false && cb_delete.IsChecked == false&&cb_addDriver.IsChecked==false)
            {
                this.Action = -1;
                this.cob_opDriver.Text = "";
                this.cob_moniDriver.Text = "";
                this.cob_moniDriverTwo.Text = "";
                InitDriverComboBox();
            }
            if (cb_addDriver.IsChecked == false)
            {
                EnableDrivers();
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.cb_modify.Checked += new RoutedEventHandler(IS_Checked);
            this.cb_add.Checked += new RoutedEventHandler(IS_Checked);
            this.cb_delete.Checked += new RoutedEventHandler(IS_Checked);
            this.cb_addDriver.Checked += new RoutedEventHandler(IS_Checked);

            this.cb_modify.Unchecked += new RoutedEventHandler(Not_Checked);
            this.cb_add.Unchecked += new RoutedEventHandler(Not_Checked);
            this.cb_delete.Unchecked += new RoutedEventHandler(Not_Checked);
            this.cb_addDriver.Unchecked += new RoutedEventHandler(Not_Checked);
            this.WindowState = WindowState.Maximized;
            this.btn_Save.IsEnabled = false;
           
            this.btn_InportDriverCombine.IsEnabled = false;
        }


        public void InitGroup()
        {
            string sql_get = "select * from GroupType";
            DataTable dt = sqlHelper.SelectDt(sql_get);
            Group.Clear();
            if (null != dt && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Group.Add(dt.Rows[i]["grp_type"].ToString(), Convert.ToInt32(dt.Rows[i]["ID"]));
                }
            }
        }

        /// <summary>
        /// 初始化从DriverCombine表里取出的数据
        /// TeamList[0] 电客车一队组合
        /// TeamList[1] 电客车二队组合
        /// ......如此类推
        /// </summary>
        private void InitTeamList()
        {
            TeamList = new List<DataRow[]>(4) { new DataRow[0], new DataRow[0], new DataRow[0], new DataRow[0] };

            string strSql = "select D.*,G.grp_type from DriverCombine D left join GroupType G on D.dcom_grp_type = G.ID where dcom_date is null and dcom_lineid = " + lineid + " order by dcom_team,dcom_NO";
            DataTable totalDT = sqlHelper.SelectDt(strSql);

            if (totalDT != null && totalDT.Rows.Count > 0)
            {
                TeamList = new List<DataRow[]>(4);
                for (int i = 0; i < 4; i++)
                {
                    string expresstion = "dcom_team = " + (i + 1).ToString();
                    //DataRow[] rrr = totalDT.Select(expresstion);
                    TeamList.Add(totalDT.Select(expresstion));
                }
            }
        }

        /// <summary>
        /// 初始化界面的司机组合
        /// </summary>
        private void InitDriverGroupList()
        {
            if (TeamList == null) { return; }

            int cout = gridList.Children.Count;
            gridList.Children.RemoveRange(4, gridList.Children.Count - 4);

            //获取最长数量
            int MaxNum = 0;
            for (int i = 0; i < TeamList.Count; i++)
            {
                if (TeamList[i].Length > MaxNum)
                {
                    MaxNum = TeamList[i].Length;
                }
            }
            for (int i = 0; i < MaxNum; i++)
            {
                gridList.RowDefinitions.Add(new RowDefinition());
            }
            panelArr = new DriverGroupCombine[TeamList.Count,100];
            for (int y = 0; y < TeamList.Count; y++)
            {
                for (int x = 0; x < TeamList[y].Length; x++)
                {
                    DriverGroupCombine item = new DriverGroupCombine(x + 1);
                    item.ID = TeamList[y][x]["ID"].ToString();
                   // item.Index = TeamList[y][x]["dcom_dutynum"].ToString();
                    item.Index = TeamList[y][x]["dcom_NO"].ToString();
                    item.Team = y + 1;                                       //设置分组

                    //主司机
                    if (Convert.IsDBNull(TeamList[y][x]["dcom_opdriver"]))
                        item.OperateDriver = "";
                    else
                        item.OperateDriver = GetUserViewNameByID(Convert.ToInt32(TeamList[y][x]["dcom_opdriver"]));
                    //副司机1
                    if (Convert.IsDBNull(TeamList[y][x]["dcom_monidriver"]))
                        item.MonitorDriver = "";
                    else
                        item.MonitorDriver = GetUserViewNameByID(Convert.ToInt32(TeamList[y][x]["dcom_monidriver"]));
                    //副司机2
                    if (Convert.IsDBNull(TeamList[y][x]["dcom_monidriverTwo"]))
                        item.MonitorDriverTwo = "";
                    else
                        item.MonitorDriverTwo = GetUserViewNameByID(Convert.ToInt32(TeamList[y][x]["dcom_monidriverTwo"]));
                    //副司机3
                    if (Convert.IsDBNull(TeamList[y][x]["dcom_monidriverThree"]))
                        item.MonitorDriverThree = "";
                    else
                        item.MonitorDriverThree = GetUserViewNameByID(Convert.ToInt32(TeamList[y][x]["dcom_monidriverThree"]));
                        
                    item.Notes = TeamList[y][x]["grp_type"].ToString();

                    item.Name = "item" + (y + 1).ToString() + item.Index;
                    this.gridList.Children.Add(item);
                    Grid.SetColumn(item, y);
                    Grid.SetRow(item, x + 1);

                    panelArr[y, x] = item;

                }
            }
        }
        private void InitDriverComboBoxAddDriver() {
            DriverList.Clear();
            string strSql = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = '" + lineid +
                     "' and user_id not in (select dcom_monidriver from DriverCombine where dcom_monidriver is not null and dcom_date is null) " +
                     " and user_id not in (select dcom_opdriver from DriverCombine where dcom_opdriver is not null and dcom_date is null) and " +
                     " user_id not in (select dcom_monidriverTwo from DriverCombine where dcom_monidriverTwo is not null and dcom_date is null) " +
                     " and user_id not in (select dcom_opdriver from DriverCombine where dcom_monidriverThree is not null and dcom_date is null) " +
                     isQuitUser +
                     " order by user_view_name";
            DataTable driverDT = sqlHelper.SelectDt(strSql);
            if (driverDT.Rows.Count > 0)
            {
                for (int i = 0; i < driverDT.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    driver.userName = driverDT.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDT.Rows[i]["user_view_name"].ToString();

                    int id = Convert.ToInt32(driverDT.Rows[i]["user_id"].ToString());

                    string item = driver.userViewName + " " + driver.userName;

                    DriverList.Add(item);
                }
            }

            this.cob_opDriver.ItemsSource = DriverList;
            this.cob_moniDriver.ItemsSource = DriverList;
            this.cob_moniDriverTwo.ItemsSource = DriverList;
            this.cob_moniDriverThree.ItemsSource = DriverList;
        }
        /// <summary>
        /// 添加的时候重新绑定司机
        /// </summary>
        private void InitDriverComBoxByAdd()
        {
            DriverList.Clear();
            //string strSql = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = '" + lineid + "'  and user_id not in (select dcom_monidriver from DriverCombine where dcom_monidriver is not null and dcom_date is null) and user_id not in (select dcom_opdriver from DriverCombine where dcom_opdriver is not null and dcom_date is null)  order by user_view_name";
            string strSql = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = '" + lineid +
                     "' and user_id not in (select dcom_monidriver from DriverCombine where dcom_monidriver is not null and dcom_date is null) " +
                     " and user_id not in (select dcom_opdriver from DriverCombine where dcom_opdriver is not null and dcom_date is null) and " +
                     " user_id not in (select dcom_monidriverTwo from DriverCombine where dcom_monidriverTwo is not null and dcom_date is null) " +
                     "and  user_id not in (select dcom_monidriverThree from DriverCombine where dcom_monidriverThree is not null and dcom_date is null)"+
                     isQuitUser +
                     " order by user_view_name";

            DataTable driverDT = sqlHelper.SelectDt(strSql);
            if (driverDT.Rows.Count > 0)
            {
                for (int i = 0; i < driverDT.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    driver.userName = driverDT.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDT.Rows[i]["user_view_name"].ToString();

                    int id = Convert.ToInt32(driverDT.Rows[i]["user_id"].ToString());

                    string item = driver.userViewName + " " + driver.userName;

                    DriverList.Add(item);
                }
            }
            this.cob_opDriver.ItemsSource = DriverList;
            this.cob_moniDriver.ItemsSource = DriverList;
            this.cob_moniDriverTwo.ItemsSource = DriverList;
            this.cob_moniDriverThree.ItemsSource = DriverList;
        }

        private void InitDriverComboBox()
        {
            DriverList.Clear();
            DicDriverInfo.Clear();
            string strSql = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = " + lineid +isQuitUser+ "  order by user_view_name";
            DataTable driverDT = sqlHelper.SelectDt(strSql);
            if (driverDT.Rows.Count > 0)
            {
                for (int i = 0; i < driverDT.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    driver.userName = driverDT.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDT.Rows[i]["user_view_name"].ToString();

                    int id = Convert.ToInt32(driverDT.Rows[i]["user_id"].ToString());

                    string item = driver.userViewName + " " + driver.userName;
                    driver.userViewNameAndUserName = item;
                    DriverList.Add(item);
                    // MonDriverList.Add(item);
                    DicDriverInfo.Add(id, driver);
                }
            }
            this.cob_opDriver.ItemsSource = DriverList;
            this.cob_moniDriver.ItemsSource = DriverList;
            this.cob_moniDriverTwo.ItemsSource = DriverList;
            this.cob_moniDriverThree.ItemsSource = DriverList;
        }

        private void InitDriverComboBoxDel()
        {
            DriverList.Clear();
            MonDriverList.Clear();
            MonDriverTwoList.Clear();
            MonDriverThreeList.Clear();
            // DicDriverInfo.Clear();
            int index = cob_Index.SelectedIndex + 1;
            string strSql = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = '" + lineid + "' "+isQuitUser+" and user_id  in (select dcom_opdriver from DriverCombine where dcom_dutynum='" + index + "' and dcom_team='" + teamID + "' and dcom_lineid='" + lineid + "' and dcom_date is null) order by user_view_name";

            string strSqlMon = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = '" + lineid + "' " + isQuitUser + "  and user_id  in (select dcom_monidriver from DriverCombine where dcom_dutynum='" + index + "' and dcom_team='" + teamID + "' and dcom_lineid='" + lineid + "' and dcom_date is null) order by user_view_name";

            string strSqlMonTwo = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = '" + lineid + "' " + isQuitUser + "  and user_id  in (select dcom_monidriverTwo from DriverCombine where dcom_dutynum='" + index + "' and dcom_team='" + teamID + "' and dcom_lineid='" + lineid + "' and dcom_date is null) order by user_view_name";

            string strSqlMonThree = "select user_id, user_name,user_view_name from [system_user] where user_dep_id =7 and user_line = '" + lineid + "' " + isQuitUser + "  and user_id  in (select dcom_monidriverThree from DriverCombine where dcom_dutynum='" + index + "' and dcom_team='" + teamID + "' and dcom_lineid='" + lineid + "' and dcom_date is null) order by user_view_name";


            DataTable driverDT = sqlHelper.SelectDt(strSql);
            DataTable driverDTMon = sqlHelper.SelectDt(strSqlMon);
            DataTable driverDTMonTwo = sqlHelper.SelectDt(strSqlMonTwo);
            DataTable driverDTMonThree = sqlHelper.SelectDt(strSqlMonThree);
            if (driverDT.Rows.Count > 0)
            {
                for (int i = 0; i < driverDT.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    driver.userName = driverDT.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDT.Rows[i]["user_view_name"].ToString();

                    int id = Convert.ToInt32(driverDT.Rows[i]["user_id"].ToString());

                    string item = driver.userViewName + " " + driver.userName;

                    DriverList.Add(item);
                }
            }

            if (driverDTMon.Rows.Count > 0)
            {
                for (int i = 0; i < driverDTMon.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    driver.userName = driverDTMon.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDTMon.Rows[i]["user_view_name"].ToString();

                    int id = Convert.ToInt32(driverDTMon.Rows[i]["user_id"].ToString());

                    string item = driver.userViewName + " " + driver.userName;

                    MonDriverList.Add(item);
                }
            }

            if (driverDTMonTwo.Rows.Count > 0)
            {
                for (int i = 0; i < driverDTMonTwo.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    driver.userName = driverDTMonTwo.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDTMonTwo.Rows[i]["user_view_name"].ToString();

                    int id = Convert.ToInt32(driverDTMonTwo.Rows[i]["user_id"].ToString());

                    string item = driver.userViewName + " " + driver.userName;

                    MonDriverTwoList.Add(item);
                }
            }
            if (driverDTMonThree.Rows.Count > 0)
            {
                for (int i = 0; i < driverDTMonThree.Rows.Count; i++)
                {
                    Driver driver = new Driver();
                    driver.userName = driverDTMonThree.Rows[i]["user_name"].ToString();
                    driver.userViewName = driverDTMonThree.Rows[i]["user_view_name"].ToString();

                    int id = Convert.ToInt32(driverDTMonThree.Rows[i]["user_id"].ToString());

                    string item = driver.userViewName + " " + driver.userName;

                    MonDriverThreeList.Add(item);
                }
            }
            this.cob_opDriver.ItemsSource = DriverList;
            this.cob_moniDriver.ItemsSource = MonDriverList;
            this.cob_moniDriverTwo.ItemsSource = MonDriverTwoList;
            this.cob_moniDriverThree.ItemsSource = MonDriverThreeList;
        }
        private void cob_team_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string team;
            try
            {
                team = ((ComboBoxItem)cob_team.SelectedItem).Content.ToString();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "错误");
                return;
            }
            teamID = GetTeamID(team);

            ReInitIndexList(teamID);
        }

        private void ReInitIndexList(int teamID)
        {
            int rowIndex = teamID - 1;
            int Max = 1;
            IndexList.Clear();
            if (TeamList != null && TeamList[rowIndex].Length > 0)
            {
                for (int i = 0; i < TeamList[rowIndex].Length; i++)
                {
                    IndexList.Add(TeamList[rowIndex][i]["dcom_NO"].ToString());
                   

                }
                Max = TeamList[rowIndex].Length + 1;
            }
            if (Action == 0 || Action == 2||Action==3)
            {
                //修改和删除只显示现有的
            }
            else if (Action == 1)
            {
                //多增加一项
                //IndexList.Clear();
                if (Max < gridList.RowDefinitions.Count)
                {
                    IndexList.Add(Max.ToString());
                }

            }
            else
            {
                if (Max < gridList.RowDefinitions.Count)
                {
                    IndexList.Add(Max.ToString());
                }
            }

        }

        private int GetTeamID(string team)
        {
            int id = 1;
            switch (team)
            {
                case "电客车一组":
                    break;
                case "电客车二组":
                    id = 2;
                    break;
                case "电客车三组":
                    id = 3;
                    break;
                case "电客车四组":
                    id = 4;
                    break;
            }
            return id;
        }

        private string GetTeamName(string team)
        {
            // int id = 1;
            string teamName = "";
            switch (team)
            {
                case "1":
                    teamName = "电客车一组";
                    break;
                case "2":
                    teamName = "电客车二组";
                    break;
                case "3":
                    teamName = "电客车三组";
                    break;
                case "4":
                    teamName = "电客车四组";
                    break;
            }
            return teamName;
        }

        private void btn_confirm_Click(object sender, RoutedEventArgs e)
        {
            if (teamID == -1)
            {
                MessageBox.Show("请选择需要进行修改的电客车队列！", "操作失败");
                return;
            }
            if (cob_Index.SelectedIndex < 0)
            {
                MessageBox.Show("请选择操作的序号", "操作失败");
                return;
            }

            if ((!string.IsNullOrEmpty(cob_opDriver.Text) && (cob_opDriver.Text == cob_moniDriver.Text||cob_opDriver.Text==cob_moniDriverTwo.Text||cob_opDriver.Text==cob_moniDriverThree.Text)||
                (!string.IsNullOrEmpty(cob_moniDriver.Text)&&(cob_moniDriver.Text==cob_moniDriverTwo.Text||cob_moniDriver.Text==cob_moniDriverThree.Text))||
                (!string.IsNullOrEmpty(cob_moniDriverTwo.Text)&&cob_moniDriverTwo.Text==cob_moniDriverThree.Text)))
            {
                MessageBox.Show("同组司机不能同一人存在两个不同位置", "操作失败");
                return;
            }
            switch (Action)
            {
                case -1:
                    MessageBox.Show("请选择操作类型！", "操作失败");
                    break;
                case 0:
                    ModifyDriverGroups();
                    //ModifyDriverGroup();
                    break;
                case 1:
                    AddDriverGroup();
                    break;
                case 2:
                    DeleteDriverGroup1();
                    break;
                case 3:
                    DriverGroupAddDriver();
                    break;
            }
            ReInitIndexList(teamID);
        }
        private void DriverGroupAddDriver() 
        {
            int index = cob_Index.SelectedIndex + 1;
            if (index > TeamList[teamID - 1].Length)
            {
                MessageBox.Show("请选择已存在的正确序号！", "操作失败");
                return;
            }
            //if (cob_opDriver.SelectedIndex < 0 && cob_moniDriver.SelectedIndex < 0 && cob_moniDriverTwo.SelectedIndex < 0)
            //{
            //    MessageBox.Show("请先选择需要进行修改的主控或副司机", "修改失败");
            //    return;
            //}
            int mubanId = -1;
            if (!cob_opDriver.IsEnabled)
            {
                
                //获取司机数据库ID
                mubanId = GetIDByUserName(cob_opDriver.SelectedItem.ToString().Split(' ')[1]);
                
            }
            else if (!cob_moniDriver.IsEnabled)
            {
                mubanId = GetIDByUserName(cob_moniDriver.SelectedItem.ToString().Split(' ')[1]);
            }
            else if (!cob_moniDriverTwo.IsEnabled)
            {
                mubanId = GetIDByUserName(cob_moniDriverTwo.SelectedItem.ToString().Split(' ')[1]);
            }
            else if (!cob_moniDriverThree.IsEnabled)
            {
                mubanId = GetIDByUserName(cob_moniDriverThree.SelectedItem.ToString().Split(' ')[1]);
            }
            else
            {
                MessageBox.Show("没有找到司机组！", "操作失败");
                return;
            }
            DataTable dt = sqlHelper.SelectDt("select * from DriverCombineCrossingRoadPlane as dccrp where dccrp.dcdr_userID="+mubanId);
            if(dt.Rows.Count==0)
            {
                MessageBox.Show("没有找到司机组！", "操作失败");
                return;
            }
            string date = cob_date.Text;
            DataTable datedt = sqlHelper.SelectDt("select t.endday from ClassTurnPlaneRecord as t where convert(datetime,'" + date + "') between convert(datetime,t.re_date) and convert(datetime,t.endday)");
            DateTime enddate = Convert.ToDateTime(datedt.Rows[0][0].ToString());
            DateTime startdate = Convert.ToDateTime(date);
            Hashtable list = new Hashtable();
            
            if (cob_opDriver.IsEnabled && cob_opDriver.SelectedIndex > -1)
            {
                int driverId = GetIDByUserName(cob_opDriver.SelectedItem.ToString().Split(' ')[1]);
                list.Add(driverId,1);
            }
            if (cob_moniDriver.IsEnabled && cob_moniDriver.SelectedIndex > -1)
            {
                int driverId = GetIDByUserName(cob_moniDriver.SelectedItem.ToString().Split(' ')[1]);
                list.Add(driverId,2);
            }
            if (cob_moniDriverTwo.IsEnabled && cob_moniDriverTwo.SelectedIndex > -1)
            {
                int driverId = GetIDByUserName(cob_moniDriverTwo.SelectedItem.ToString().Split(' ')[1]);
                list.Add(driverId, 3);
            }
            if (cob_moniDriverThree.IsEnabled && cob_moniDriverThree.SelectedIndex > -1)
            {
                int driverId = GetIDByUserName(cob_moniDriverThree.SelectedItem.ToString().Split(' ')[1]);
                list.Add(driverId, 4);
            }

            foreach (int id in list.Keys)
            {
                int years = enddate.Year - startdate.Year;
                int months = enddate.Month - startdate.Month;
                int days = enddate.Day;
                string sql = "insert into DriverCombineCrossingRoadPlane";
            }

        }
        private bool DriverHasSwitchedRecord(int userid, string startDate,string endDate) {
            string checkHasSwitchedRecordSql = "select s.id,s.applyDayAppMonthID,s.backToDayBackMonthID from SwitchedRecord as s " +
                //"left join DriverCombineCrossingRoadPlane as t on t.id=s.applyDayAppMonthID "+
                //" left join DriverCombineCrossingRoadPlane as t1 on t1.id=s.backToDayBackMonthID "+
    " where (s.sr_applicant='" + userid + "' and convert(datetime,s.sr_chgdate) between convert(datetime,'" + startDate + "') and convert(datetime,'" + endDate + "') ) or (s.sr_changer='" + userid + "' and convert(datetime,s.sr_appdate) between convert(datetime,'" + startDate + "') and convert(datetime,'" + endDate + "') )";
            DataTable dt = sqlHelper.SelectDt(checkHasSwitchedRecordSql);
            if (dt.Rows.Count > 0)
                return true;
            return false;
        }
        private int GetTeamNullCount(DriverIn di) {

            int i = 0;
            if (di == null)
                return i;
            if (string.IsNullOrEmpty(di._monDriver))
                i++;
            if (string.IsNullOrEmpty(di._monDriverTwo))
                i++;
            if (string.IsNullOrEmpty(di._opDriver))
                i++;
            if (string.IsNullOrEmpty(di._monDriverThree))
                i++;
            return i;
        }
        private void ModifyDriverGroups()
        {
            int state = -1;
            int index = cob_Index.SelectedIndex + 1;
            string[] opDriver = null;
            string[] moniDriver = null;
            string[] moniDriverTwo = null;
            string[] moniDriverThree = null;
            int opID = -1;
            int moniID = -1;
            int moniTwoID = -1;
            int moniThreeID = -1;
            bool isnoupdate = true;

            DriverIn opDriverIn = null;
            DriverIn moniDriverIn = null;
            DriverIn moniDriverTwoIn = null;
            DriverIn moniDriverThreeIn = null;

            if (index > TeamList[teamID - 1].Length)
            {
                MessageBox.Show("请选择已存在的正确序号！", "操作失败");
                return;
            }
            if (cob_opDriver.SelectedIndex < 0 && cob_moniDriver.SelectedIndex < 0 && cob_moniDriverTwo.SelectedIndex < 0 && cob_moniDriverThree.SelectedIndex<0)
            {
                MessageBox.Show("请先选择需要进行修改的主控或副司机", "修改失败");
                return;
            }
            int tempIndex = index; 
            index = GetIndexByNO(index);




            //获取该序号的三个司机
            if (cob_opDriver.SelectedIndex > -1)
            {
                //获取司机编号
                opDriver = cob_opDriver.SelectedItem.ToString().Split(' ');
                //获取司机数据库ID
                opID = GetIDByUserName(opDriver[1]);

                if (ISDriverIn(opID, out opDriverIn, teamID.ToString(), index.ToString(), "Opdriver")) { state = 0; }
            }
            //第一个副司机
            if (cob_moniDriver.SelectedIndex > -1)
            {
                moniDriver = cob_moniDriver.SelectedItem.ToString().Split(' ');
                moniID = GetIDByUserName(moniDriver[1]);
                if (ISDriverIn(moniID, out moniDriverIn, teamID.ToString(), index.ToString(), "Monidriver"))
                {
                    if (state == 0) { state = 2; }
                    else { state = 1; }
                }
            }
            //第二个副司机
            if (cob_moniDriverTwo.SelectedIndex > -1)
            {
                moniDriverTwo = cob_moniDriverTwo.SelectedItem.ToString().Split(' ');
                moniTwoID = GetIDByUserName(moniDriverTwo[1]);
                if (ISDriverIn(moniTwoID, out moniDriverTwoIn, teamID.ToString(), index.ToString(), "MonidriverTwo"))
                {

                    if (state == 0) { state = 2; }
                    else { state = 1; }
                }
            }
            //第三个副司机
            if (cob_moniDriverThree.SelectedIndex > -1)
            {
                moniDriverThree = cob_moniDriverThree.SelectedItem.ToString().Split(' ');
                moniThreeID = GetIDByUserName(moniDriverThree[1]);
                if (ISDriverIn(moniThreeID, out moniDriverThreeIn, teamID.ToString(), index.ToString(), "MonidriverThree"))
                {

                    if (state == 0) { state = 2; }
                    else { state = 1; }
                }
            }

            string strSql = "";
            ArrayList sqlList = new ArrayList();
            string srcTeam = cob_team.Text;

            //DataTable datedt = sqlHelper.SelectDt("select t.endday from ClassTurnPlaneRecord as t where convert(datetime,'" + date + "') between convert(datetime,t.re_date) and convert(datetime,t.endday)");
            //DateTime enddate = Convert.ToDateTime(datedt.Rows[0][0].ToString());
            //DateTime startdate = Convert.ToDateTime(date);
            //cob_date
            //" where dcom_team =" + teamID + " and dcom_dutynum='" + index + "' and dcom_lineid ='" + lineid + "' and dcom_date is null";



            string getSrcTeamSql = "select dc.*,s1.user_view_name as dcom_opdriverName,s2.user_view_name as dcom_monidriverName,s3.user_view_name as dcom_monidriverNameTwo from DriverCombine as dc left join [system_user] as s1 on s1.user_id=dc.dcom_opdriver left join [system_user] as s2 on s2.user_id=dc.dcom_monidriver left join [system_user] as s3 on s3.user_id=dc.dcom_monidriverTwo left join [system_user] as s4 on s4.user_id=dc.dcom_monidriverThree  where dc.dcom_team = '" + teamID + "' and dc.dcom_date is null and dc.dcom_dutynum='" + index + "' and dc.dcom_lineid='" + lineid + "'";
            DataTable srcTeamDt = sqlHelper.SelectDt(getSrcTeamSql);
            if (srcTeamDt.Rows.Count == 0)
            {
                MessageBoxHelper.ShowTips("没有找到相关记录");
                return;
            }
            int srcOpdriverId = -1, srcMoniDriverId =-1, srcMoniDriverTwoId = -1 , srcMoniDriverThreeId=-1;
            if (srcTeamDt.Rows.Count > 0)
            {
                if (srcTeamDt.Rows[0]["dcom_opdriver"] != null && srcTeamDt.Rows[0]["dcom_opdriver"] != DBNull.Value)
                    srcOpdriverId = Convert.ToInt32(srcTeamDt.Rows[0]["dcom_opdriver"]);
                if (srcTeamDt.Rows[0]["dcom_monidriver"] != null && srcTeamDt.Rows[0]["dcom_monidriver"] != DBNull.Value)
                    srcMoniDriverId = Convert.ToInt32(srcTeamDt.Rows[0]["dcom_monidriver"]);
                if (srcTeamDt.Rows[0]["dcom_monidriverTwo"] != null && srcTeamDt.Rows[0]["dcom_monidriverTwo"] != DBNull.Value)
                    srcMoniDriverTwoId = Convert.ToInt32(srcTeamDt.Rows[0]["dcom_monidriverTwo"]);
                if (srcTeamDt.Rows[0]["dcom_monidriverThree"] != null && srcTeamDt.Rows[0]["dcom_monidriverThree"] != DBNull.Value)
                    srcMoniDriverThreeId = Convert.ToInt32(srcTeamDt.Rows[0]["dcom_monidriverThree"]);
            }
            string date = cob_date.Text;
            DataTable datedt = sqlHelper.SelectDt("select t.endday,t.id,t.re_date from ClassTurnPlaneRecord as t where line=" + lineid + " and  convert(datetime,'" + date + "') between convert(datetime,t.re_date) and convert(datetime,t.endday)");
            if (datedt.Rows.Count == 0 || datedt.Rows[0][0] == DBNull.Value)
            {
                MessageBoxHelper.ShowTips("指定日期无排版记录，不允许修改");
                return;
            }
            //DateTime enddate = Convert.ToDateTime(datedt.Rows[0][0].ToString());
            //DateTime startdate = Convert.ToDateTime(date);
            string enddate = datedt.Rows[0][0].ToString();
            string sameTeamChangeMsg = "同组司机调换位置，第一步：先将位置B的司机置空，第二步：将位置A的司机替换为原来位置B的司机，第三步：设置位置B的司机未原来位置A的司机";

            string wherestr = null;
            if (srcOpdriverId!=-1)
                wherestr += " dcc.dcdr_userID=" + srcOpdriverId.ToString();
            if (srcMoniDriverId!=-1){
                if (wherestr != null)
                    wherestr += " or ";
                wherestr += " dcc.dcdr_userID=" + srcMoniDriverId.ToString();
            }
            if(srcMoniDriverTwoId!=-1)
            {
                if(wherestr!=null)
                    wherestr += " or ";
                wherestr += " dcc.dcdr_userID=" + srcMoniDriverTwoId.ToString();
            }
            if (srcMoniDriverThreeId != -1)
            {
                if(wherestr!=null)
                    wherestr += " or ";
                wherestr += " dcc.dcdr_userID=" + srcMoniDriverThreeId.ToString();
            }
            if (opID != -1)
            {
                if (wherestr != null)
                    wherestr += " or ";
                wherestr += " dcc.dcdr_userID=" + opID;
            }
            if (moniID != -1)
            {
                if (wherestr != null)
                    wherestr += " or ";
                wherestr += " dcc.dcdr_userID=" + moniID;
            }
            if (moniTwoID != -1) {
                if (wherestr != null)
                    wherestr += " or ";
                wherestr += " dcc.dcdr_userID=" + moniTwoID;
            }
            if (moniThreeID != -1) {
                if (wherestr != null)
                    wherestr += " or ";
                wherestr += " dcc.dcdr_userID=" + moniThreeID;
            }
            DataTable lunbanDt = sqlHelper.SelectDt("select  dcc.* from DriverCombineCrossingRoadPlane as dcc where (" + wherestr + ") and dcc.dcdr_date between convert(datetime,'"+date+"') and convert(datetime,'"+enddate+"')");


            if (cob_cb_lunban.IsChecked.Value)
            {


                //如果有调班记录，则不允许置空司机位置
                if (srcOpdriverId != -1 && opID == -1)
                {
                    if (DriverHasSwitchedRecord(srcOpdriverId, date, enddate))
                    {
                        MessageBoxHelper.ShowTips("主司机有调班记录，不能删除");
                        return;
                    }
                }
                else if (srcOpdriverId == -1 && opDriverIn != null && GetTeamName(opDriverIn._team.ToString()) != srcTeam)
                {
                    if (DriverHasSwitchedRecord(opID, date, enddate))
                    {

                        MessageBoxHelper.ShowTips("司机" + opDriver[0] + "有调班记录，不能更换");
                        return;
                    }
                }
                if (srcMoniDriverId != -1 && moniID == -1)
                {
                    if (DriverHasSwitchedRecord(srcMoniDriverId, date, enddate))
                    {
                        MessageBoxHelper.ShowTips("副司机二有调班记录，不能删除");
                        return;
                    }
                }
                else if (srcMoniDriverId == -1 && moniDriverIn != null && GetTeamName(moniDriverIn._team.ToString()) != srcTeam)
                {
                    if (DriverHasSwitchedRecord(moniID, date, enddate))
                    {
                        MessageBoxHelper.ShowTips("司机" + moniDriver[0] + "有调班记录，不能更换");
                        return;
                    }
                }


                if (srcMoniDriverTwoId != -1 && moniTwoID == -1)
                {
                    if (DriverHasSwitchedRecord(srcMoniDriverTwoId, date, enddate))
                    {
                        MessageBoxHelper.ShowTips("副司机二有调班记录，不能删除");
                        return;
                    }
                }
                else if (srcMoniDriverTwoId == -1 && moniDriverTwoIn != null && GetTeamName(moniDriverTwoIn._team.ToString()) != srcTeam)
                {
                    if (DriverHasSwitchedRecord(moniTwoID, date, enddate))
                    {
                        MessageBoxHelper.ShowTips("司机" + moniDriverTwo[0] + "有调班记录，不能更换");
                        return;
                    }
                }

                if (srcMoniDriverThreeId != -1 && moniThreeID == -1)
                {
                    if (DriverHasSwitchedRecord(srcMoniDriverThreeId, date, enddate))
                    {
                        MessageBoxHelper.ShowTips("副司机三有调班记录，不能删除");
                        return;
                    }
                }
                else if (srcMoniDriverThreeId == -1 && moniDriverThreeIn != null && GetTeamName(moniDriverThreeIn._team.ToString()) != srcTeam)
                {
                    if (DriverHasSwitchedRecord(moniThreeID, date, enddate))
                    {
                        MessageBoxHelper.ShowTips("司机" + moniDriverThree[0] + "有调班记录，不能更换");
                        return;
                    }
                }

                if (opDriverIn != null)
                {
                    //代号说明 A：主司机         B：副司机1       C：副司机2               D：副司机3
                    string dteam = GetTeamName(opDriverIn._team.ToString());

                    if (srcOpdriverId == -1&&dteam!=srcTeam)
                    {
                        
                        if (moniDriverIn != null && moniDriverIn._team == opDriverIn._team && moniDriverIn._index == opDriverIn._index && srcMoniDriverId == -1)
                        {//A=B

                            if (moniDriverTwoIn != null && moniDriverTwoIn._team == opDriverIn._team && moniDriverTwoIn._index == opDriverIn._index && srcMoniDriverTwoId == -1)//而且A=C
                            {

                                if (moniDriverThreeIn != null && moniDriverThreeIn._team == opDriverIn._team && moniDriverThreeIn._index == opDriverIn._index && srcMoniDriverThreeId == -1)//而且A=D
                                {
                                    MessageBoxHelper.ShowTips("调换后" + GetTeamName(moniDriverTwoIn._team.ToString()) + "序号" + moniDriverTwoIn._dcomNO + "为空，不允许修改");
                                    return;
                                }
                                else if (GetTeamNullCount(opDriverIn) >= 1)//A=B=D!=D，那么只要一个为空，就不允许
                                {
                                    MessageBoxHelper.ShowTips("调换后" + GetTeamName(opDriverIn._team.ToString()) + "序号" + opDriverIn._dcomNO + "为空，不允许修改");
                                    return;
                                }

                            }
                            else if (moniDriverThreeIn != null && moniDriverThreeIn._team == opDriverIn._team && moniDriverThreeIn._index == opDriverIn._index && srcMoniDriverThreeId == -1 && GetTeamNullCount(opDriverIn) >= 1)//A！=C但是A=D，那么只要一个为空，就不允许
                            {
                                MessageBoxHelper.ShowTips("调换后" + GetTeamName(opDriverIn._team.ToString()) + "序号" + opDriverIn._dcomNO + "为空，不允许修改");
                                return;
                            }
                            else if (GetTeamNullCount(opDriverIn) >= 2)//A=B!=C!=D，那么两个为空的话就不允许
                            {
                                MessageBoxHelper.ShowTips("调换后" + GetTeamName(opDriverIn._team.ToString()) + "序号" + opDriverIn._dcomNO + "为空，不允许修改");
                                return;
                            }
                        }
                        else if (moniDriverTwoIn!=null&&moniDriverTwoIn._team == opDriverIn._team && moniDriverTwoIn._index == opDriverIn._index && srcMoniDriverTwoId == -1)//A!=B但是A=C
                        {
                            if (moniDriverThreeIn != null && moniDriverThreeIn._team == opDriverIn._team && moniDriverThreeIn._index == opDriverIn._index && srcMoniDriverThreeId == -1 && GetTeamNullCount(opDriverIn) >= 1)//A=C=D!=B，那么1个为空就不允许
                            {
                                MessageBoxHelper.ShowTips("调换后" + GetTeamName(opDriverIn._team.ToString()) + "序号" + opDriverIn._dcomNO + "为空，不允许修改");
                                return;
                            }else if (GetTeamNullCount(opDriverIn) >= 2)
                            {
                                MessageBoxHelper.ShowTips("调换后" + GetTeamName(opDriverIn._team.ToString()) + "序号" + opDriverIn._dcomNO + "为空，不允许修改");
                                return;
                            }
                        }
                        else//A!=B A!=C A!=D
                        {
                            if (GetTeamNullCount(opDriverIn) >= 3)
                            {
                                MessageBoxHelper.ShowTips("调换后" + GetTeamName(opDriverIn._team.ToString()) + "序号" + opDriverIn._dcomNO + "为空，不允许修改");
                                return;
                            }
                        }

                    }





                    //如果不是同一组的情况，那么当司机有换班记录时不允许调换
                    if (dteam != srcTeam)
                    {

                        if (DriverHasSwitchedRecord(opDriverIn._userId, cob_date.Text, enddate))
                        {
                            MessageBoxHelper.ShowTips("司机" + opDriver[0] + "在指定日期有调班记录，不能修改");
                            return;
                        }
                        if (srcOpdriverId != -1 && DriverHasSwitchedRecord(Convert.ToInt32(srcOpdriverId), cob_date.Text, enddate))
                        {
                            MessageBoxHelper.ShowTips("司机" + srcTeamDt.Rows[0]["dcom_opdriverName"] + "在指定日期有调班记录，不能修改");
                            return;
                        }

                    }
                    else if (opDriverIn._index == Convert.ToInt32(srcTeamDt.Rows[0]["dcom_dutynum"]))//如果是同队，则提示不允许操作，需要分步
                    {
                        MessageBoxHelper.ShowTips(sameTeamChangeMsg);
                        return;
                    }
                }
                if (moniDriverIn != null)
                {
                    string dteam = GetTeamName(moniDriverIn._team.ToString());
                    if (srcMoniDriverId == -1 && dteam != srcTeam)
                    {
                        if (moniDriverTwoIn != null && srcMoniDriverTwoId == -1 && moniDriverTwoIn._team == moniDriverIn._team && moniDriverIn._index == moniDriverTwoIn._index)//B=C
                        {
                            if (moniDriverThreeIn != null && srcMoniDriverThreeId == -1 && moniDriverThreeIn._team == moniDriverIn._team && moniDriverIn._index == moniDriverThreeIn._index && GetTeamNullCount(moniDriverIn) >= 1)
                            {
                                MessageBoxHelper.ShowTips("调换后" + GetTeamName(moniDriverIn._team.ToString()) + "序号" + moniDriverIn._dcomNO + "为空，不允许修改");
                                return;
                            }
                            else if (GetTeamNullCount(moniDriverIn) >= 2)
                            {
                                MessageBoxHelper.ShowTips("调换后" + GetTeamName(moniDriverIn._team.ToString()) + "序号" + moniDriverIn._dcomNO + "为空，不允许修改");
                                return;
                            }
                            //if (GetTeamNullCount(moniDriverIn) >= 1)
                            //{
                            //    MessageBoxHelper.ShowTips("调换后" + GetTeamName(moniDriverIn._team.ToString()) + "序号" + moniDriverIn._index + "为空，不允许修改");
                            //    return;
                            //}
                        }
                        else
                        {
                            if (GetTeamNullCount(moniDriverIn) >= 3)
                            {
                                MessageBoxHelper.ShowTips("调换后" + GetTeamName(moniDriverIn._team.ToString()) + "序号" + moniDriverIn._dcomNO + "为空，不允许修改");
                                return;
                            }
                        }
                    }

                    
                    //如果不是同一组的情况，那么当司机有换班记录时不允许调换
                    if (dteam != srcTeam)
                    {

                        if (DriverHasSwitchedRecord(moniDriverIn._userId, cob_date.Text, enddate))
                        {
                            MessageBoxHelper.ShowTips("司机" + moniDriver[0] + "在指定日期有调班记录，不能修改");
                            return;
                        }
                        if (srcMoniDriverId != -1 && DriverHasSwitchedRecord(Convert.ToInt32(srcMoniDriverId), cob_date.Text, enddate))
                        {
                            MessageBoxHelper.ShowTips("司机" + srcTeamDt.Rows[0]["dcom_monidriverName"] + "在指定日期有调班记录，不能修改");
                            return;
                        }

                    }
                    else if (moniDriverIn._index == Convert.ToInt32(srcTeamDt.Rows[0]["dcom_dutynum"]))//如果是同队，则提示不允许操作，需要分步
                    {
                        MessageBoxHelper.ShowTips(sameTeamChangeMsg);
                        return;
                    }
                }

                if (moniDriverTwoIn != null)
                {
                    string dteam = GetTeamName(moniDriverTwoIn._team.ToString());
                    if (srcMoniDriverTwoId == -1&&dteam!=srcTeam)
                    {
                        if (moniDriverThreeIn != null && srcMoniDriverThreeId == -1 && moniDriverThreeIn._team == moniDriverTwoIn._team && moniDriverTwoIn._index == moniDriverThreeIn._index&&GetTeamNullCount(moniDriverTwoIn)>=2)//C=D
                        {
                            MessageBoxHelper.ShowTips("调换后" + GetTeamName(moniDriverTwoIn._team.ToString()) + "序号" + moniDriverTwoIn._dcomNO + "为空，不允许修改");
                        }
                        else if (GetTeamNullCount(moniDriverTwoIn) >=3 )
                        {
                            MessageBoxHelper.ShowTips("调换后" + GetTeamName(moniDriverTwoIn._team.ToString()) + "序号" + moniDriverTwoIn._dcomNO + "为空，不允许修改");
                            return;
                        }
                    }

                    
                    //如果不是同一组的情况，那么当司机有换班记录时不允许调换
                    if (dteam != srcTeam)
                    {
                        if (DriverHasSwitchedRecord(moniDriverTwoIn._userId, cob_date.Text, enddate))
                        {
                            MessageBoxHelper.ShowTips("司机" + moniDriverTwo[0] + "在指定日期有调班记录，不能修改");
                            return;
                        }
                        if (srcMoniDriverTwoId != -1 && DriverHasSwitchedRecord(Convert.ToInt32(srcMoniDriverTwoId), cob_date.Text, enddate))
                        {
                            MessageBoxHelper.ShowTips("司机" + srcTeamDt.Rows[0]["dcom_monidriverNameTwo"] + "在指定日期有调班记录，不能修改");
                            return;
                        }

                    }
                    else if (moniDriverTwoIn._index == Convert.ToInt32(srcTeamDt.Rows[0]["dcom_dutynum"]))//如果是同队，则提示不允许操作，需要分步
                    {
                        MessageBoxHelper.ShowTips("同组司机调换位置，请分两步操作");
                        return;
                    }
                }

                if (moniDriverThreeIn != null)
                {
                    string dteam = GetTeamName(moniDriverThreeIn._team.ToString());
                    if (srcMoniDriverThreeId == -1&&dteam!=srcTeam)
                    {
                       if (GetTeamNullCount(moniDriverThreeIn) >= 3)
                        {
                            MessageBoxHelper.ShowTips("调换后" + GetTeamName(moniDriverThreeIn._team.ToString()) + "序号" + moniDriverThreeIn._dcomNO + "为空，不允许修改");
                            return;
                        }
                    }

                    
                    //如果不是同一组的情况，那么当司机有换班记录时不允许调换
                    if (dteam != srcTeam)
                    {
                        if (DriverHasSwitchedRecord(moniDriverThreeIn._userId, cob_date.Text, enddate))
                        {
                            MessageBoxHelper.ShowTips("司机" + moniDriverThree[0] + "在指定日期有调班记录，不能修改");
                            return;
                        }
                        if (srcMoniDriverThreeId != -1 && DriverHasSwitchedRecord(Convert.ToInt32(srcMoniDriverThreeId), cob_date.Text, enddate))
                        {
                            MessageBoxHelper.ShowTips("司机" + srcTeamDt.Rows[0]["dcom_monidriverNameThree"] + "在指定日期有调班记录，不能修改");
                            return;
                        }

                    }
                    else if (moniDriverThreeIn._index == Convert.ToInt32(srcTeamDt.Rows[0]["dcom_dutynum"]))//如果是同队，则提示不允许操作，需要分步
                    {
                        MessageBoxHelper.ShowTips(sameTeamChangeMsg);
                        return;
                    }
                }

            }

            if (state >= 0) //如果有司机已经在分组
            {



                string mess = GetWarnMessage(new DriverIn[]{opDriverIn,moniDriverIn,moniDriverTwoIn,moniDriverThreeIn});

                if (!MessageBoxHelper.ConfirmYesNo(string.Format("{0} \n确认需要进行分组更新吗？", mess)))
                {
                    return;
                }
            }

            strSql = "update DriverCombine set ";
            string updateInfo = "";
            if (opDriver != null && opDriver.Length > 0)
            {
                //主司机
                updateInfo = updateInfo + "dcom_opdriver = '" + opID + "'";
            }
            else
            {
                updateInfo = updateInfo + "dcom_opdriver = null ";
            }
            if (moniDriver != null)
            {
                //副司机
                if (string.IsNullOrEmpty(updateInfo))
                {
                    updateInfo = updateInfo + "dcom_monidriver = '" + moniID + "'";
                }
                else
                {
                    updateInfo = updateInfo + ", dcom_monidriver = '" + moniID + "'";
                }

            }
            else
                updateInfo += ", dcom_monidriver = null ";
            if (moniDriverTwo != null)
            {
                //副司机2
                if (string.IsNullOrEmpty(updateInfo))
                {
                    updateInfo = updateInfo + "dcom_monidriverTwo = '" + moniTwoID + "'";
                }
                else
                {
                    updateInfo = updateInfo + ", dcom_monidriverTwo = '" + moniTwoID + "'";
                }
            }
            else
                updateInfo += ", dcom_monidriverTwo = null ";

            if (moniDriverThree != null)
            {
                //副司机3
                if (string.IsNullOrEmpty(updateInfo))
                {
                    updateInfo = updateInfo + "dcom_monidriverThree = '" + moniThreeID + "'";
                }
                else
                {
                    updateInfo = updateInfo + ", dcom_monidriverThree = '" + moniThreeID + "'";
                }
            }
            else
            {
                updateInfo += ", dcom_monidriverThree = null ";
            }

            string updateDriverCombineFormat1 = "update DriverCombine set {0} = {5} where {0}={1} and dcom_lineid = {2} and (dcom_date is null or dcom_date between '{3}' and '{4}')";
            string updateDriverCombineFormat2 = "update DriverCombine set {0} = {3} where {0}={1} and dcom_lineid = {2} and dcom_date is null";

            for (int dp = 0; dp < 4;dp++ ) {
                DriverIn driverIn = null;
                int srcDriverId = -1;
                if (dp == 0)
                {
                    driverIn = opDriverIn;
                    srcDriverId = srcOpdriverId;
                }
                else if (dp == 1)
                {
                    driverIn = moniDriverIn;
                    srcDriverId = srcMoniDriverId;
                }
                else if (dp == 2){
                    driverIn = moniDriverTwoIn;
                    srcDriverId = srcMoniDriverTwoId;
                }
                else if (dp == 3)
                {
                    driverIn = moniDriverThreeIn;
                    srcDriverId = srcMoniDriverTwoId;
                }
                else
                    break;
                if (driverIn != null)
                {
                    string sql = "";
                    if (driverIn._type == "Opdriver")
                    {
                        string type = "dcom_opdriver";
                        if (cob_cb_lunban.IsChecked.Value)
                        {
                            if (srcDriverId == -1)
                                sql = string.Format(updateDriverCombineFormat1, type, driverIn._userId, lineid, date, enddate, "NULL");
                            else
                                sql = string.Format(updateDriverCombineFormat1, type, driverIn._userId, lineid, date, enddate, srcDriverId);
                        }
                        else
                        {
                            if (srcDriverId == -1)
                                sql = string.Format(updateDriverCombineFormat2, type, driverIn._userId, lineid, "NULL");
                            else
                                sql = string.Format(updateDriverCombineFormat2, type, driverIn._userId, lineid, srcDriverId);
                        }
                    }
                    else if (driverIn._type == "Monidriver")
                    {
                        string type = "dcom_monidriver";
                        if (cob_cb_lunban.IsChecked.Value)
                        {
                            if (srcDriverId == -1)
                                sql = string.Format(updateDriverCombineFormat1, type, driverIn._userId, lineid, date, enddate, "NULL");
                            else
                                sql = string.Format(updateDriverCombineFormat1, type, driverIn._userId, lineid, date, enddate, srcDriverId);
                        }
                        else
                        {
                            if (srcDriverId == -1)
                                sql = string.Format(updateDriverCombineFormat2, type, driverIn._userId, lineid, "NULL");
                            else
                                sql = string.Format(updateDriverCombineFormat2, type, driverIn._userId, lineid, srcDriverId);
                        }
                    }
                    else if (driverIn._type == "MonidriverTwo")
                    {
                        string type = "dcom_monidriverTwo";
                        if (cob_cb_lunban.IsChecked.Value)
                        {
                            if (srcDriverId == -1)
                                sql = string.Format(updateDriverCombineFormat1, type, driverIn._userId, lineid, date, enddate, "NULL");
                            else
                                sql = string.Format(updateDriverCombineFormat1, type, driverIn._userId, lineid, date, enddate, srcDriverId);
                        }
                        else
                        {
                            if (srcDriverId == -1)
                                sql = string.Format(updateDriverCombineFormat2, type, driverIn._userId, lineid, "NULL");
                            else
                                sql = string.Format(updateDriverCombineFormat2, type, driverIn._userId, lineid, srcDriverId);
                        }
                    }
                    else if (driverIn._type == "MonidriverThree")
                    {
                        string type = "dcom_monidriverThree";
                        if (cob_cb_lunban.IsChecked.Value)
                        {
                            if (srcDriverId == -1)
                                sql = string.Format(updateDriverCombineFormat1, type, driverIn._userId, lineid, date, enddate, "NULL");
                            else
                                sql = string.Format(updateDriverCombineFormat1, type, driverIn._userId, lineid, date, enddate, srcDriverId);
                        }
                        else
                        {
                            if (srcDriverId == -1)
                                sql = string.Format(updateDriverCombineFormat2, type, driverIn._userId, lineid, "NULL");
                            else
                                sql = string.Format(updateDriverCombineFormat2, type, driverIn._userId, lineid, srcDriverId);
                        }
                    }
                    sqlHelper.ExecuteSql(sql);
                }
            }
            if (srcOpdriverId == -1 || srcMoniDriverId == -1 || srcMoniDriverTwoId == -1 || srcMoniDriverThreeId == -1)
            {
                string sql = "select * from DriverCombine where  dcom_lineid='" + lineid + "' and dcom_date is null and dcom_opdriver is null and dcom_monidriver is null and dcom_monidriverTwo is null and dcom_monidriverThree is null";
                DataTable emptyRowDt = sqlHelper.SelectDt(sql);
                for (int i = 0; i < emptyRowDt.Rows.Count;i++ )
                {
                    DataRow row = emptyRowDt.Rows[i];
                    int team=Convert.ToInt32(row["dcom_team"]);
                    int dindex=Convert.ToInt32( row["dcom_dutynum"]);
                    int dcomNo=Convert.ToInt32(row["dcom_NO"]);
                    string strsql = string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", team, dindex, lineid);
                    sqlHelper.ExecuteSql(strsql);
                    //sqlHelper.ExecuteSql(strsqlup);
                    UpdateDutyNumAndNo(team,dindex,dcomNo);
                    if (team == teamID && dindex < index)
                    {
                        index--;
                    }
                }
            }

            //更新修改后的司机组的数据
            strSql += updateInfo + " where dcom_team =" + teamID + " and dcom_dutynum='" + index + "' and dcom_lineid ='" + lineid + "' ";
            //string updateDriverCombineSql = strSql+=" and dcom_date='?'";

            strSql += " and dcom_date is null";
            if (sqlHelper.ExecuteSql(strSql) > 0)
            {
                RefreshIndexComboBox();
                InitDriverGroupList();


                if (cob_cb_lunban.IsChecked.Value)
                {
                    //修改轮班
                    DateTime sd = Convert.ToDateTime(cob_date.Text);
                    DateTime ed = Convert.ToDateTime(enddate);

                    string updateLunbanSql = "";
                    DataTable dctable=sqlHelper.SelectDt("select dc1.id from drivercombine as dc1 where dc1.dcom_team =" + teamID + " and dc1.dcom_dutynum='" + index + "' and dc1.dcom_lineid ='" + lineid + "'  and dc1.dcom_date is null");

                    updateLunbanSql += "update dc set dc.dcom_opdriver=dc1.dcom_opdriver,dc.dcom_monidriver=dc1.dcom_monidriver,dc.dcom_monidriverTwo=dc1.dcom_monidriverTwo,dc.dcom_monidriverThree=dc1.dcom_monidriverThree from DriverCombine as dc,DriverCombine as dc1 where dc.dcom_parents=dc1.id and dc1.dcom_team =" + teamID + " and dc1.dcom_dutynum='" + index + "' and dc1.dcom_lineid ='" + lineid + "'  and dc1.dcom_date is null and dc.dcom_date between '" + sd.ToString("yyyy-MM-dd") + "' and '" + ed.ToString("yyyy-MM-dd") + "';";

                    string lunbanDeleteSqlFormat = "delete from DriverCombineCrossingRoadPlane where dcdr_date between convert(datetime,'{0}') and convert(datetime,'{1}') and dcdr_userID={2};";
                    
                    ArrayList updateSwitchedSql = new ArrayList();
                    string updateDriverCombineIdList = "";
                    if (lunbanDt.Rows.Count > 0)
                    {

                        string updateDccrpFormat = "update DriverCombineCrossingRoadPlane set isback={0},dcdr_reamrkNew={1},replaceDriver={2},dcdr_userID={3},dcdr_userName={4},dcdr_type={6} where id={5};";
                        string updateOpDriverFormat = " update DriverCombineCrossingRoadPlane set dcom_opdriver=dc.dcom_opdriver,dcom_opdriverName=(case  when dc.dcom_opdriver is null then  null else  s1.user_view_name end)" +
                            " from DriverCombine as dc,[system_user] as s1 " +
                            " where dcdr_driverCombineId in ({0})" + " and dcdr_date between '{1}' and '{2}' and line={3}" +
    " and dcdr_driverCombineId=dc.id and (dc.dcom_opdriver is null or dc.dcom_opdriver=s1.user_id);";

                        string updateMoniDriverFormat = " update DriverCombineCrossingRoadPlane set dcom_monidriver=dc.dcom_monidriver, dcom_monidriverName=(case when dc.dcom_monidriver is null then null else s2.user_view_name end)" +
                        " from DriverCombine as dc,[system_user] as s2 " +
                         " where dcdr_driverCombineId in ({0})" + " and dcdr_date between '{1}' and '{2}' and line={3}  and dcdr_driverCombineId=dc.id " +
                         " and (dc.dcom_monidriver is null or dc.dcom_monidriver=s2.user_id);";

                        string updateMoniTwoDriverFormat = "update DriverCombineCrossingRoadPlane set dcom_monidriverTwo=dc.dcom_monidriverTwo,dcom_monidriverNameTwo=(case when dc.dcom_monidriverTwo is null then null else s3.user_view_name end)" +
                            " from DriverCombine as dc,[system_user] as s3 " +
                            " where dcdr_driverCombineId in ({0})" + " and dcdr_date between '{1}' and '{2}' and line={3}  and dcdr_driverCombineId=dc.id " +
                            " and (dc.dcom_monidriverTwo is null or dc.dcom_monidriverTwo=s3.user_id);";

                        string updateMoniThreeDriverFormat="update DriverCombineCrossingRoadPlane set dcom_monidriverThree=dc.dcom_monidriverThree,dcom_monidriverNameThree=(case when dc.dcom_monidriverThree is null then null else s4.user_view_name end) " +
                            " from DriverCombine as dc,[system_user] as s4 " +
                            " where dcdr_driverCombineId in ({0})" + " and dcdr_date between '{1}' and '{2}' and line={3}  and dcdr_driverCombineId=dc.id " +
                            " and (dc.dcom_monidriverThree is null or dc.dcom_monidriverThree=s4.user_id);";

                        for (int i = 0; i < 4; i++)
                        {
                            //1表示主司机，2表示副司机1,3表示副司机2,4表示副司机3
                            int sourceId;
                            int targetId;
                            string targetName=null;
                            DriverIn targetIn=null;
                            int type = -1;
                            switch (i)
                            {
                                case 0:
                                    sourceId = srcOpdriverId;
                                    targetId = opID;
                                    type = 1;
                                    if (targetId != -1)
                                    {
                                        targetName = opDriver[0];
                                        targetIn = opDriverIn;
                                    }

                                    break;
                                case 1:
                                    sourceId = srcMoniDriverId;
                                    targetId = moniID;
                                    type = 2;
                                    if (targetId != -1)
                                    {
                                        targetName = moniDriver[0];
                                        targetIn = moniDriverIn;
                                    }

                                    break;
                                case 2:
                                    sourceId = srcMoniDriverTwoId;
                                    targetId = moniTwoID;
                                    type = 3;
                                    if (targetId != -1)
                                    {
                                        targetName = moniDriverTwo[0];
                                        targetIn = moniDriverTwoIn;
                                    }
                                    break;
                                case 3:
                                    sourceId = srcMoniDriverThreeId;
                                    targetId = moniThreeID;
                                    type = 4;
                                    if (targetId != -1)
                                    {
                                        targetName = moniDriverThree[0];
                                        targetIn = moniDriverThreeIn;
                                    }
                                    break;
                                default:
                                    return;
                            }
                            // || (sourceId != -1 && targetIn==null &&targetId!=-1)
                            DataTable dtSourceDg = null,dtTargetDg=null;
                            if (sourceId != -1)
                            {
                                dtSourceDg = sqlHelper.SelectDt("select * from drivergroup where dgrp_user_id=" + sourceId);
                            }
                            if (targetId != -1)
                                dtTargetDg = sqlHelper.SelectDt("select * from drivergroup where dgrp_user_id="+targetId);

                            if ((targetId == -1 && sourceId != -1))
                            {
                                DataRow[] srows = lunbanDt.Select("dcdr_date='" + date + "' and dcdr_userID=" + sourceId);
                                if (sd.Date == DateTime.Now.Date && dtSourceDg !=null && dtSourceDg.Rows.Count > 0)
                                {
                                    updateLunbanSql += "delete from drivergroup where id=" + dtSourceDg.Rows[0]["id"]+";";
                                }
                                updateLunbanSql += string.Format(lunbanDeleteSqlFormat, date,enddate, sourceId);
                                
                                //sourceId
                                updateDriverCombineIdList+=srows[0]["dcdr_driverCombineId"]+",";
                            }
                            else if (targetId != -1 && sourceId == -1)
                            {
                                DateTime dt = new DateTime(sd.Year, sd.Month, sd.Day);

                                updateLunbanSql += string.Format(lunbanDeleteSqlFormat, date, enddate, targetId);
                                string updateSwitchFormat = "update SwitchedRecord set {0}={1} , {2}=dccrp.dcdr_duty from DriverCombineCrossingRoadPlane as dccrp where dccrp.dcdr_userid={3} and dccrp.dcdr_date='{4}' and {0}={5};";
                                while (dt <= ed)
                                {

                                    DataRow[] srows = lunbanDt.Select("dcdr_date='" + dt.ToString("yyyy-MM-dd") + "' and (dcdr_userID=" + srcOpdriverId + " or dcdr_userID=" + srcMoniDriverId + " or dcdr_userID=" + srcMoniDriverTwoId + " or dcdr_userID="+srcMoniDriverThreeId+")");
                                    DataRow[] trows = lunbanDt.Select("dcdr_date='" + dt.ToString("yyyy-MM-dd") + "' and dcdr_userID=" + targetId);

                                    if (dt.Date == DateTime.Now.Date)
                                    {
                                        DataTable dtDc = sqlHelper.SelectDt("select id from drivercombine where dcom_parents=" + srows[0]["dcdr_driverCombineId"]+" and dcom_date='"+dt.Date.ToString("yyyy-MM-dd")+"'");
                                        DataTable dtDg = sqlHelper.SelectDt("select * from drivergroup where dgrp_dcom_id=" + dtDc.Rows[0]["id"]);
                                        if (dtTargetDg != null && dtTargetDg.Rows.Count > 0)
                                            updateLunbanSql += "update drivergroup set dgrp_dcom_id=" + dtDc.Rows[0]["id"] + ",attenTime='" + srows[0]["dcdr_crossAttenTime"] + "' where id=" + dtTargetDg.Rows[0]["id"] + ";";
                                        else if(dtDg!=null&&dtDg.Rows.Count>0)
                                        {
                                            updateLunbanSql += "insert into drivergroup(dgrp_user_id,dgrp_line,dgrp_date,dgrp_dcom_id,dgrp_srd_id,dgrp_attendtime,dgrp_outtime,dgrp_room,replaceDriver,dgrp_pbyInfo,attenTime) values(" + targetId + ",'" + CONSTDATA.UserModel.Line + "'," + GetValue(dtDg.Rows[0]["dgrp_date"]) + "," + GetValue(dtDg.Rows[0]["dgrp_dcom_id"]) + ",NULL," + GetValue(dtDg.Rows[0]["dgrp_attendtime"]) + "," + GetValue(dtDg.Rows[0]["dgrp_outtime"]) + "," + GetValue(dtDg.Rows[0]["dgrp_room"]) + ",NULL," + GetValue(dtDg.Rows[0]["dgrp_pbyInfo"]) + "," + GetValue(dtDg.Rows[0]["attenTime"]) + ");";
                                        }
                                    }
                                    if (trows.Length > 0)
                                    {
                                        
                                        updateLunbanSql += GetInsertLunBanSql(srows[0], targetId, trows[0]["dcdr_userName"].ToString(), type, trows[0]["replaceDriver"].ToString(), trows[0]["isback"].ToString(), dt.ToString("yyyy-MM-dd"));
                                        string tempVariable = "@updateSwitchedRecord2_" + targetId + "_" + dt.ToString("yyyyMMdd");
                                        updateLunbanSql += " declare " + tempVariable + " int; set " + tempVariable + "= @@IDENTITY;";
                                        updateLunbanSql += string.Format(updateSwitchFormat, "applyDayAppMonthID", tempVariable, "sr_appnum",  "sr_SouceApplicant", dt.ToString("yyyyMMdd"),trows[0]["id"]);
                                        updateLunbanSql += string.Format(updateSwitchFormat, "backToDayBackMonthID", tempVariable, "sr_chgnum", "sr_SouceChanger", dt.ToString("yyyyMMdd"), trows[0]["id"]);
                                    }
                                    else {
                                        updateLunbanSql += GetInsertLunBanSql(srows[0], targetId, targetName, type, "NULL", "NULL",dt.ToString("yyyy-MM-dd"));
                                    }
                                    
                                    updateSwitchedSql .Add( DriverTeamViewModel.setMonthPlaneInfoByDriverIDandDate(targetId.ToString(), dt.ToString("yyyy-MM-dd")));
                                    dt = dt.AddDays(1);
                                }
                                

                                DataRow[] arows = lunbanDt.Select("dcdr_date='" + date + "' and (dcdr_userID=" + srcOpdriverId + " or dcdr_userID=" + srcMoniDriverId + " or dcdr_userID=" + srcMoniDriverTwoId + " or dcdr_userID="+srcMoniDriverThreeId+")");
                                DataRow[]  brows = lunbanDt.Select("dcdr_date='" + dt.ToString("yyyy-MM-dd") + "' and dcdr_userID=" + targetId);
                                updateDriverCombineIdList+=arows[0]["dcdr_driverCombineId"]+",";
                                if(brows.Length>0)
                                    updateDriverCombineIdList+=brows[0]["dcdr_driverCombineId"]+",";
                            }
                            else if (targetId != -1 && sourceId != -1 && targetId != sourceId)
                            {

                                DateTime dt = new DateTime(sd.Year, sd.Month, sd.Day);
                                while (dt <= ed)
                                {

                                    DataRow[] srows = lunbanDt.Select("dcdr_date='" + dt.ToString("yyyy-MM-dd") + "' and dcdr_userID=" + sourceId);
                                    if (targetIn != null)
                                    {
                                        
                                        DataRow[] trows = lunbanDt.Select("dcdr_date='" + dt.ToString("yyyy-MM-dd") + "' and dcdr_userID=" + targetId);

                                        if (dt.Date == DateTime.Now.Date && dtTargetDg != null && dtTargetDg.Rows.Count > 0)
                                        {
                                            DataTable dtDc = sqlHelper.SelectDt("select id from drivercombine where dcom_parents=" + srows[0]["dcdr_driverCombineId"] + " and dcom_date='" + dt.Date.ToString("yyyy-MM-dd") + "'");
                                            updateLunbanSql += "update drivergroup set dgrp_dcom_id=" + dtDc.Rows[0]["id"] + ",attenTime=" + GetValue(srows[0]["dcdr_crossAttenTime"]) + " where id=" + dtTargetDg.Rows[0]["id"] + ";";
                                        }
                                        if (dt.Date == DateTime.Now.Date && dtSourceDg != null && dtSourceDg.Rows.Count > 0)
                                        {
                                            DataTable dtDc = sqlHelper.SelectDt("select id from drivercombine where dcom_parents=" + GetValue(trows[0]["dcdr_driverCombineId"]) + " and dcom_date='" + dt.Date.ToString("yyyy-MM-dd") + "'");
                                            updateLunbanSql += "update drivergroup set dgrp_dcom_id=" + GetValue(dtDc.Rows[0]["id"]) + ",attenTime=" + GetValue(trows[0]["dcdr_crossAttenTime"]) + " where id=" + dtSourceDg.Rows[0]["id"] + ";";
                                        }

                                        updateLunbanSql += string.Format(updateDccrpFormat, GetValue(trows[0]["isback"]), GetValue(trows[0]["dcdr_reamrkNew"]), GetValue(trows[0]["replaceDriver"]), targetId, GetValue(trows[0]["dcdr_userName"]), srows[0]["id"],srows[0]["dcdr_type"]);
                                        updateLunbanSql += string.Format(updateDccrpFormat, GetValue(srows[0]["isback"]), GetValue(srows[0]["dcdr_reamrkNew"]), GetValue(srows[0]["replaceDriver"]), sourceId, GetValue(srows[0]["dcdr_userName"]), trows[0]["id"], trows[0]["dcdr_type"]);


                                        updateLunbanSql += "update SwitchedRecord set  sr_appnum=dccrp.dcdr_duty from DriverCombineCrossingRoadPlane as dccrp where dccrp.dcdr_userid=sr_SouceApplicant and dccrp.dcdr_date='" + dt.ToString("yyyy-MM-dd") + "' and (applyDayAppMonthID=" + srows[0]["id"] + " or applyDayAppMonthID=" + trows[0]["id"]+");";
                                        updateLunbanSql += "update SwitchedRecord set applyDayAppMonthID=(select case when applyDayAppMonthID=" + srows[0]["id"] + " then " + trows[0]["id"] + " else " + srows[0]["id"] + " end) from DriverCombineCrossingRoadPlane as dccrp where (applyDayAppMonthID=" + srows[0]["id"] + ") or (applyDayAppMonthID=" + trows[0]["id"]+");";
                                        
                                        updateLunbanSql += "update SwitchedRecord set  sr_chgnum=dccrp.dcdr_duty from DriverCombineCrossingRoadPlane as dccrp where dccrp.dcdr_userid=sr_SouceChanger and dccrp.dcdr_date='" + dt.ToString("yyyy-MM-dd") + "' and (backToDayBackMonthID=" + srows[0]["id"] + " or backToDayBackMonthID=" + trows[0]["id"]+");";
                                        updateLunbanSql += "update SwitchedRecord set backToDayBackMonthID=(select case when backToDayBackMonthID=" + srows[0]["id"] + " then " + trows[0]["id"] + " else " + srows[0]["id"] + " end) where backToDayBackMonthID=" + srows[0]["id"] + " or backToDayBackMonthID=" + trows[0]["id"]+";";

                                        updateSwitchedSql.Add(DriverTeamViewModel.setMonthPlaneInfoByDriverIDandDate(sourceId.ToString(), dt.ToString("yyyy-MM-dd")));
                                        updateSwitchedSql.Add(DriverTeamViewModel.setMonthPlaneInfoByDriverIDandDate(targetId.ToString(), dt.ToString("yyyy-MM-dd")));
                                    }
                                    else
                                    {
                                        updateLunbanSql += string.Format(updateDccrpFormat, "NULL", "NULL", "NULL", targetId, GetValue(targetName), srows[0]["id"], srows[0]["dcdr_type"]);
                                        
                                        updateSwitchedSql.Add(DriverTeamViewModel.setMonthPlaneInfoByDriverIDandDate(targetId.ToString(), dt.ToString("yyyy-MM-dd")));
                                    }
                                    dt = dt.AddDays(1);
                                }

                                DataRow[] arows = lunbanDt.Select("dcdr_date='" + date + "' and dcdr_userID=" + sourceId);
                                DataRow[] brows = lunbanDt.Select("dcdr_date='" + date + "' and dcdr_userID=" + targetId);
                                updateDriverCombineIdList+=arows[0]["dcdr_driverCombineId"]+",";
                                if(brows.Length>0)
                                    updateDriverCombineIdList+=brows[0]["dcdr_driverCombineId"]+",";
                            }

                        }

                        updateLunbanSql += "update sr set sr.sr_appnum=dccrp.dcdr_duty from SwitchedRecord as sr,DriverCombineCrossingRoadPlane as dccrp where sr.sr_SouceApplicant=dccrp.dcdr_userID and sr.sr_appnum<>dccrp.dcdr_duty and dccrp.dcdr_date=sr.sr_appdate;"+
"update sr set sr.sr_chgnum=dccrp.dcdr_duty from SwitchedRecord as sr,DriverCombineCrossingRoadPlane as dccrp where sr.sr_SouceChanger=dccrp.dcdr_userID and sr.sr_chgnum<>dccrp.dcdr_duty and dccrp.dcdr_date=sr.sr_appdate;";

                        if (!string.IsNullOrEmpty(updateDriverCombineIdList))
                        {
                            updateDriverCombineIdList = updateDriverCombineIdList.Remove(updateDriverCombineIdList.Length-1);
                            updateLunbanSql += string.Format(updateOpDriverFormat, updateDriverCombineIdList, date, enddate, lineid);
                            updateLunbanSql += string.Format(updateMoniDriverFormat, updateDriverCombineIdList, date, enddate, lineid);
                            updateLunbanSql += string.Format(updateMoniTwoDriverFormat, updateDriverCombineIdList, date, enddate, lineid);
                            updateLunbanSql += string.Format(updateMoniThreeDriverFormat, updateDriverCombineIdList, date, enddate, lineid);

                        }
                    }

                    if (sd != Convert.ToDateTime(datedt.Rows[0]["re_date"]))
                    {
                        updateLunbanSql += "update ClassTurnPlaneRecord set endDay='" + Convert.ToDateTime(date).AddDays(-1).ToString("yyyy-MM-dd") + "' where id=" + datedt.Rows[0]["id"].ToString() + ";";
                        updateLunbanSql += "insert into ClassTurnPlaneRecord values('" + date + "'," + lineid + ",getdate(),'" + enddate + "');";
                    }

                    sqlHelper.ExecuteSql(updateLunbanSql);


                    for (int i = 0; i < updateSwitchedSql.Count; i++)
                    {
                        string sql = updateSwitchedSql[i].ToString();
                        sqlHelper.ExecuteSql(sql);
                    }

                    sqlHelper.ExecuteSql("insert into AdjustDcReturnRecord(id,recordDate,lineid,adr_user,action_type) values(newid(),getdate()," + CONSTDATA.UserModel.Line + "," + CONSTDATA.UserModel.ID + ",'修改班组');");
                }


                MessageBoxHelper.ShowTips(string.Format("修改电客车{0}队 序号{1} 的司机分组成功！", teamID, tempIndex));
            }

            else
            {
                MessageBoxHelper.ShowError(string.Format("修改电客车{0}队 序号{1} 的司机分组失败！", teamID, tempIndex));

            }

        }
        public string GetValue(object obj)
        {
            if (obj==null||obj == DBNull.Value)
                return "NULL";
            return "'"+obj.ToString()+"'";
        }
        private string GetInsertLunBanSql(DataRow row, int id, string name,int type,string replaceDriver,string isback,string date)
        {
            if (string.IsNullOrEmpty(replaceDriver) )
                replaceDriver = "NULL";
            return " insert into DriverCombineCrossingRoadPlane values(" + GetValue(row["line"]) + "," +
                                GetValue(row["dcdr_team"]) + "," + GetValue(row["dcdr_cls_id"]) + "," + GetValue(row["dcdr_drivercombineId"]) + "," +
                                GetValue(row["dcdr_drivertype"]) + "," + GetValue(row["dcdr_tabletimeid"]) + "," + GetValue(row["dcdr_tabletimename"]) + "," +
                                GetValue(row["dcdr_crossid"]) + "," + GetValue(row["dcdr_crossNum"]) + "," +
                                GetValue(row["dcdr_crosszby"]) + "," + GetValue(row["dcdr_crosstype"]) + "," + GetValue(row["dcdr_crossAttenPlace"]) + "," +
                                GetValue(row["dcdr_crossAttenTime"]) + "," + GetValue(row["dcdr_crossofftime"]) + "," + GetValue(row["dcdr_crossoffplace"]) + "," +
                                GetValue(row["dcdr_remark"]) + ",'" + date + "'," + GetValue(row["dcdr_dutynum"]) + "," +
                                GetValue(row["dcom_opdriver"]) + "," + GetValue(row["dcom_opdriverName"]) + "," + GetValue(row["dcom_monidriver"]) + "," +
                                GetValue(row["dcom_monidrivername"]) + "," + GetValue(row["dcdr_ybarrive"]) + "," + id + ",'" + name + "'," +
                                GetValue(row["sourcemiles"]) + "," + GetValue(row["sourcewHours"]) + "," + GetValue(row["dcom_monidriverTwo"]) + "," +
                                GetValue(row["dcom_monidriverNameTwo"]) + ","+replaceDriver+"," + GetValue(row["sourcemiles"]) + "," + GetValue(row["sourcewHours"]) + ","+type+"," +
                                GetValue(row["dcom_NO"]) + "," + GetValue(row["dcdr_duty"]) + ",NULL,NULL,NULL," + GetValue(row["dcom_monidriverThree"]) + "," +
                                GetValue(row["dcom_monidriverNameThree"])+");";
        }

        #region 该方法不用
        private void ModifyDriverGroup()
        {
            // state : 0，opDriver in；1：opDriver not in，moniDriver in ; 2：both in；
            int state = -1;
            int index = cob_Index.SelectedIndex + 1;
            string[] opDriver = null;
            string[] moniDriver = null;
            string[] moniDriverTwo = null;
            int opID = -1;
            int moniID = -1;
            int moniTwoID = -1;

            DriverIn opDriverIn = null;
            DriverIn moniDriverIn = null;
            DriverIn moniDriverTwoIn = null;

            if (index > TeamList[teamID - 1].Length)
            {
                MessageBox.Show("请选择已存在的正确序号！", "操作失败"); return;
            }
            if (cob_opDriver.SelectedIndex < 0 && cob_moniDriver.SelectedIndex < 0 && cob_moniDriverTwo.SelectedIndex < 0)
            {
                MessageBox.Show("请先选择需要进行修改的主控或副司机", "修改失败"); return;
            }

            //获取该序号的三个司机
            if (cob_opDriver.SelectedIndex > -1)
            {
                //获取司机编号
                opDriver = cob_opDriver.SelectedItem.ToString().Split(' ');
                //获取司机数据库ID
                opID = GetIDByUserName(opDriver[1]);

                if (ISDriverIn(opID, out opDriverIn, teamID.ToString(), index.ToString(), "Opdriver")) { state = 0; }
            }
            //第一个副司机
            if (cob_moniDriver.SelectedIndex > -1)
            {
                moniDriver = cob_moniDriver.SelectedItem.ToString().Split(' ');
                moniID = GetIDByUserName(moniDriver[1]);
                if (ISDriverIn(moniID, out moniDriverIn, teamID.ToString(), index.ToString(), "Monidriver"))
                {
                    if (state == 0) { state = 2; }
                    else { state = 1; }
                }
            }
            //第二个副司机
            if (cob_moniDriverTwo.SelectedIndex > -1)
            {
                moniDriverTwo = cob_moniDriverTwo.SelectedItem.ToString().Split(' ');
                moniTwoID = GetIDByUserName(moniDriverTwo[1]);
                if (ISDriverIn(moniTwoID, out moniDriverTwoIn, teamID.ToString(), index.ToString(), "MonidriverTwo"))
                {

                    if (state == 0) { state = 2; }
                    else { state = 1; }
                }
            }




            string strSql = "";
            ArrayList sqlList = new ArrayList();

            if (state >= 0) //如果有司机已经在分组
            {
                string mess = GetWarnMessage(new DriverIn[]{opDriverIn,moniDriverIn,moniDriverTwoIn});

                if (!MessageBoxHelper.ConfirmYesNo(string.Format("{0} \n确认需要进行分组更新吗？", mess)))
                {
                    return;
                }
            }

            strSql = "update DriverCombine set ";
            string updateInfo = "";
            if (opDriver != null && opDriver.Length > 0)
            {
                //主司机
                updateInfo = updateInfo + "dcom_opdriver = '" + opID + "'";
            }
            if (moniDriver != null)
            {
                //副司机
                if (string.IsNullOrEmpty(updateInfo))
                {
                    updateInfo = updateInfo + "dcom_monidriver = '" + moniID + "'";
                }
                else
                {
                    updateInfo = updateInfo + ", dcom_monidriver = '" + moniID + "'";
                }

            }
            if (moniDriverTwo != null)
            {
                //副司机2
                if (string.IsNullOrEmpty(updateInfo))
                {
                    updateInfo = updateInfo + "dcom_monidriverTwo = '" + moniTwoID + "'";
                }
                else
                {
                    updateInfo = updateInfo + ", dcom_monidriverTwo = '" + moniTwoID + "'";
                }
            }

            // and  = " + index + " and dcom_lineid = " + lineid
            strSql = strSql + updateInfo + "where dcom_team =" + teamID + " and dcom_dutynum='" + index + "' and dcom_lineid ='" + lineid + "' and dcom_date is null";
            #region 华丽丽的注释
            //if (opDriver != null && opDriver.Length > 0)  //修改主控
            //{
            /* strSql = "update DriverCombine set dcom_opdriver = '" + opID + "' where dcom_team =" + teamID + " and dcom_dutynum = " + index + " and dcom_lineid = " + lineid;

             if (moniDriver != null && opDriver.Length > 0) //修改主控和监控
             {
                    
                 strSql = "update DriverCombine set dcom_opdriver = '" + opID + "',dcom_monidriver = '" + moniID + "' where dcom_team =" + teamID + " and dcom_dutynum = " + index + " and dcom_lineid = " + lineid;
             }*/

            //}
            /* else if (moniDriver != null && opDriver == null) //只修改副司机
             {
                 strSql = "update DriverCombine set dcom_monidriver = '" + moniID + "' where dcom_team =" + teamID + " and dcom_dutynum = " + index + " and dcom_lineid = " + lineid; 
             }*/
            #endregion
            if (string.IsNullOrEmpty(updateInfo)) { return; }
            sqlList.Add(strSql);
            //已存在分组的司机更新为空
            #region 华丽丽的注释
            /* if (null != opDriverIn)
            {
                if (null != moniDriverIn)
                {
                    if (opDriverIn._team == moniDriverIn._team && opDriverIn._index == moniDriverIn._index) //如果是同一组的同时被更新了，那就删除该行
                    {
                        if (opDriverIn._index == index && moniDriverIn._index == index) // add bin 如果被替换的都在同一组 说明只是正副司机换位而已
                        { }
                        else
                        {
                            sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2}", opDriverIn._team, opDriverIn._index, lineid));
                        }
                         
                       
                    }
                    else
                    {
                        sqlList.Add(string.Format("update DriverCombine set dcom_opdriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2}", opDriverIn._team, opDriverIn._index, lineid));
                        sqlList.Add(string.Format("update DriverCombine set dcom_monidriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2}", moniDriverIn._team, moniDriverIn._index, lineid));
                    }
                }
                else
                {
                    sqlList.Add(string.Format("update DriverCombine set dcom_opdriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2}", opDriverIn._team, opDriverIn._index, lineid));
                }
            }
            else if (null != moniDriverIn)
            {
                sqlList.Add(string.Format("update DriverCombine set dcom_monidriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2}", moniDriverIn._team, moniDriverIn._index, lineid));
            }*/
            #endregion 华丽丽的注释

            //===============================================

            //===============================================

            /////////这部分逻辑不是很清楚，添加第二个副司机后可能会修改出错////////////////
            //主司机已经存在分组，两个副司机不存在分组
            if (null != opDriverIn && null == moniDriverIn && null == moniDriverTwoIn)
            {

                if (opDriverIn._type == "Opdriver")
                {

                    sqlList.Add(string.Format("update DriverCombine set dcom_opdriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", opDriverIn._team, opDriverIn._index, lineid));
                    //判断副司机1、2是否有人,没有的话删除
                    if (string.IsNullOrEmpty(opDriverIn._monDriver) && string.IsNullOrEmpty(opDriverIn._monDriverTwo))
                    {
                        sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", opDriverIn._team, opDriverIn._index, lineid));
                        //sqlList.Add("update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_team =" + opDriverIn._team + " and dcom_dutynum >" + opDriverIn._index + " and dcom_date is null and dcom_lineid = " + lineid);
                        sqlList.AddRange(GetUpdateDutyNumAndNoScript(opDriverIn._team, opDriverIn._index, opDriverIn._dcomNO));
                    }

                }
                else if (opDriverIn._type == "Monidriver")
                {
                    sqlList.Add(string.Format("update DriverCombine set dcom_monidriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", opDriverIn._team, opDriverIn._index, lineid));
                    //判断主司机、副司机2是否有人,没有的话删除
                    if (string.IsNullOrEmpty(opDriverIn._opDriver) && string.IsNullOrEmpty(opDriverIn._monDriverTwo))
                    {
                        sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", opDriverIn._team, opDriverIn._index, lineid));
                        //sqlList.Add("update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_team =" + opDriverIn._team + " and dcom_dutynum >" + opDriverIn._index + " and dcom_date is null and dcom_lineid = " + lineid);
                        sqlList.AddRange(GetUpdateDutyNumAndNoScript(opDriverIn._team, opDriverIn._index, opDriverIn._dcomNO));
                    }
                }
                else if (opDriverIn._type == "MonidriverTwo")
                {
                    sqlList.Add(string.Format("update DriverCombine set dcom_monidriverTwo = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", opDriverIn._team, opDriverIn._index, lineid));
                    //判断主司机、副司机1是否有人,没有的话删除
                    if (string.IsNullOrEmpty(opDriverIn._opDriver) && string.IsNullOrEmpty(opDriverIn._monDriver))
                    {
                        sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", opDriverIn._team, opDriverIn._index, lineid));
                        //sqlList.Add("update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_team =" + opDriverIn._team + " and dcom_dutynum >" + opDriverIn._index + " and dcom_date is null and dcom_lineid = " + lineid);
                        sqlList.AddRange(GetUpdateDutyNumAndNoScript(opDriverIn._team, opDriverIn._index, opDriverIn._dcomNO));
                    }

                }

                //}
            }
            if (null != moniDriverIn && null == opDriverIn && null == moniDriverTwoIn)
            {
                //if (moniDriverIn._index != index || moniDriverIn.monId==opID)
                //{
                // sqlList.Add(string.Format("update DriverCombine set dcom_monidriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2}", moniDriverIn._team, moniDriverIn._index, lineid));
                //}


                if (moniDriverIn._type == "Opdriver")
                {
                    sqlList.Add(string.Format("update DriverCombine set dcom_opdriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverIn._team, moniDriverIn._index, lineid));
                    //判断监控是否有人 没有的话删除
                    if (string.IsNullOrEmpty(moniDriverIn._monDriver) && string.IsNullOrEmpty(moniDriverIn._monDriverTwo))
                    {
                        sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverIn._team, moniDriverIn._index, lineid));
                        //sqlList.Add("update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_team =" + moniDriverIn._team + " and dcom_dutynum >" + moniDriverIn._index + " and dcom_date is null and dcom_lineid = " + lineid);
                        sqlList.AddRange(GetUpdateDutyNumAndNoScript(moniDriverIn._team, moniDriverIn._index, moniDriverIn._dcomNO));
                    }
                }
                else if (moniDriverIn._type == "Monidriver")
                {
                    sqlList.Add(string.Format("update DriverCombine set dcom_monidriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverIn._team, moniDriverIn._index, lineid));
                    //判断主控是否有人 没有的话删除
                    if (string.IsNullOrEmpty(moniDriverIn._opDriver) && string.IsNullOrEmpty(moniDriverIn._monDriverTwo))
                    {
                        sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverIn._team, moniDriverIn._index, lineid));
                        //sqlList.Add("update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_date is null and dcom_team =" + moniDriverIn._team + " and dcom_dutynum >" + moniDriverIn._index + " and dcom_lineid = " + lineid);
                        sqlList.AddRange(GetUpdateDutyNumAndNoScript(moniDriverIn._team, moniDriverIn._index, moniDriverIn._dcomNO));
                    }
                }
                else if (moniDriverIn._type == "MonidriverTwo")
                {
                    sqlList.Add(string.Format("update DriverCombine set dcom_monidriverTwo = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverIn._team, moniDriverIn._index, lineid));
                    //判断主控是否有人 没有的话删除
                    if (string.IsNullOrEmpty(moniDriverIn._opDriver) && string.IsNullOrEmpty(moniDriverIn._monDriver))
                    {
                        sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverIn._team, moniDriverIn._index, lineid));
                        //sqlList.Add("update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_date is null and dcom_team =" + moniDriverIn._team + " and dcom_dutynum >" + moniDriverIn._index + " and dcom_lineid = " + lineid);
                        sqlList.AddRange(GetUpdateDutyNumAndNoScript(moniDriverIn._team, moniDriverIn._index, moniDriverIn._dcomNO));
                    }

                }

            }
            if (null == moniDriverIn && null == opDriverIn && null != moniDriverTwoIn)
            {
                //if (moniDriverIn._index != index || moniDriverIn.monId==opID)
                //{
                // sqlList.Add(string.Format("update DriverCombine set dcom_monidriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2}", moniDriverIn._team, moniDriverIn._index, lineid));
                //}


                if (moniDriverTwoIn._type == "Opdriver")
                {
                    sqlList.Add(string.Format("update DriverCombine set dcom_opdriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverTwoIn._team, moniDriverTwoIn._index, lineid));
                    //判断监控是否有人 没有的话删除
                    if (string.IsNullOrEmpty(moniDriverTwoIn._monDriver) && string.IsNullOrEmpty(moniDriverIn._monDriverTwo))
                    {
                        sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverTwoIn._team, moniDriverTwoIn._index, lineid));
                        //sqlList.Add("update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_team =" + moniDriverTwoIn._team + " and dcom_dutynum >" + moniDriverTwoIn._index + " and dcom_date is null and dcom_lineid = " + lineid);
                        sqlList.AddRange(GetUpdateDutyNumAndNoScript(moniDriverTwoIn._team, moniDriverTwoIn._index, moniDriverTwoIn._dcomNO));
                    }
                }
                else if (moniDriverTwoIn._type == "Monidriver")
                {
                    sqlList.Add(string.Format("update DriverCombine set dcom_monidriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverIn._team, moniDriverIn._index, lineid));
                    //判断主控是否有人 没有的话删除
                    if (string.IsNullOrEmpty(moniDriverTwoIn._opDriver) && string.IsNullOrEmpty(moniDriverIn._monDriverTwo))
                    {
                        sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverTwoIn._team, moniDriverTwoIn._index, lineid));
                        //sqlList.Add("update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_date is null and dcom_team =" + moniDriverTwoIn._team + " and dcom_dutynum >" + moniDriverTwoIn._index + " and dcom_lineid = " + lineid);
                        sqlList.AddRange(GetUpdateDutyNumAndNoScript(moniDriverTwoIn._team, moniDriverTwoIn._index, moniDriverTwoIn._dcomNO));

                    }
                }
                else if (moniDriverTwoIn._type == "MonidriverTwo")
                {
                    sqlList.Add(string.Format("update DriverCombine set dcom_monidriverTwo = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverIn._team, moniDriverIn._index, lineid));
                    //判断主控是否有人 没有的话删除
                    if (string.IsNullOrEmpty(moniDriverTwoIn._opDriver) && string.IsNullOrEmpty(moniDriverIn._monDriver))
                    {
                        sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverTwoIn._team, moniDriverTwoIn._index, lineid));
                        //sqlList.Add("update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_date is null and dcom_team =" + moniDriverTwoIn._team + " and dcom_dutynum >" + moniDriverTwoIn._index + " and dcom_lineid = " + lineid);
                        sqlList.AddRange(GetUpdateDutyNumAndNoScript(moniDriverTwoIn._team, moniDriverTwoIn._index, moniDriverTwoIn._dcomNO));
                    }

                }

            }
            if (null != opDriverIn && null != moniDriverIn && null != moniDriverTwoIn)
            {
                if (opDriverIn._team == moniDriverIn._team && moniDriverIn._team == moniDriverTwoIn._team && opDriverIn._index == moniDriverIn._index && moniDriverIn._index == moniDriverTwoIn._index) //如果是同一组的同时被更新了，那就删除该行
                {
                    if (opDriverIn._index == index && moniDriverIn._index == index && moniDriverTwoIn._index == index && opDriverIn._team == teamID)
                    { }
                    else
                    {
                        //两组都被替换直接删除不解释
                        sqlList.Add(string.Format("delete from DriverCombine where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", opDriverIn._team, opDriverIn._index, lineid));
                        //sqlList.Add("update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_date is null and dcom_team =" + opDriverIn._team + " and dcom_dutynum >" + opDriverIn._index + " and dcom_lineid = " + lineid);
                        sqlList.AddRange(GetUpdateDutyNumAndNoScript(opDriverIn._team, opDriverIn._index, opDriverIn._dcomNO));
                    }
                }
                else
                {
                    sqlList.Add(string.Format("update DriverCombine set dcom_opdriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", opDriverIn._team, opDriverIn._index, lineid));
                    sqlList.Add(string.Format("update DriverCombine set dcom_monidriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", moniDriverIn._team, moniDriverIn._index, lineid));
                }
            }



            if (sqlHelper.ExecuteSqlTran(sqlList))
            {
                RefreshIndexComboBox();
                InitDriverGroupList();

                MessageBoxHelper.ShowTips(string.Format("修改电客车{0}队 序号{1} 的司机分组成功！", teamID, index));
            }
        }
        #endregion
        private string GetWarnMessage(DriverIn driver)
        {
            string duty="",msg="";
            if (driver != null)
            {
                if (driver._type == "Opdriver")
                {
                    duty = "主司机";
                }
                else if (driver._type == "Monidriver")
                {
                    duty = "副司机";
                }
                else if (driver._type == "MonidriverTwo")
                {
                    duty = "副司机";
                }
                else
                {
                    duty = "副司机";
                }
                msg += string.Format("副司机 {0} ,已存在 {1} 序号为 {2} 的 {3}中", this.GetUserViewNameByID(driver._userId), GetTeamName(driver._team.ToString()), driver._dcomNO, duty);
            }
            return msg;
        }


        private string GetWarnMessage(DriverIn[] drivers)
        {
            string msg = "";
            for (int i = 0; i < drivers.Length;i++ )
            {
                msg += GetWarnMessage(drivers[i]);
            }
            return msg;
        }
        /// <summary>
        /// 废弃代码
        /// </summary>
        /// <param name="opDriver"></param>
        /// <param name="moniDriver"></param>
        /// <param name="moniDriverTwo"></param>
        /// <param name="moniDriverThree"></param>
        /// <returns></returns>
        private string GetWarnMessage(DriverIn opDriver, DriverIn moniDriver, DriverIn moniDriverTwo,DriverIn moniDriverThree)
        {

            //修改提示语
            //获取司机的位置 
            string opDuty = "";
            string monDuty = "";
            string monTwoDuty = "";
            string monThreeDuty = "";
            if (opDriver != null)
            {
                if (opDriver._type == "Opdriver")
                {
                    opDuty = "主司机";
                }
                else if (opDriver._type == "Monidriver")
                {
                    opDuty = "副司机";
                }
                else
                {
                    opDuty = "副司机";
                }
            }
            if (moniDriver != null)
            {
                if (moniDriver._type == "Opdriver")
                {
                    monDuty = "主司机";
                }
                else if (moniDriver._type == "Monidriver")
                {
                    monDuty = "副司机";
                }
                else
                {
                    monDuty = "副司机";
                }
            }
            if (moniDriverTwo != null)
            {
                if (moniDriverTwo._type == "Opdriver")
                {
                    monTwoDuty = "主司机";
                }
                else if (moniDriverTwo._type == "Monidriver")
                {
                    monTwoDuty = "副司机";
                }
                else
                {
                    monTwoDuty = "副司机";
                }
            }
            if (moniDriverThree != null)
            {
                if (moniDriverThree._type == "Opdriver")
                {
                    monThreeDuty = "主司机";
                }
                else if (moniDriverThree._type == "Monidriver")
                {
                    monThreeDuty = "副司机";
                }
                else
                {
                    monThreeDuty = "副司机";
                }
            }

            string mess = "";
            if (null != opDriver)
            {
                mess += string.Format("主司机 {0} ,已存在 {1} 序号为 {2} 的 {3}中", this.GetUserViewNameByID(opDriver._userId), GetTeamName(opDriver._team.ToString()), opDriver._dcomNO, opDuty);

                if (null != moniDriver)
                {
                    mess += "\n";
                    mess += string.Format("副司机 {0} ,已存在 {1} 序号为 {2} 的 {3}中", this.GetUserViewNameByID(moniDriver._userId), GetTeamName(moniDriver._team.ToString()), moniDriver._dcomNO.ToString(), monDuty);
                }
                if (null != moniDriverTwo)
                {
                    mess += "\n";
                    mess += string.Format("副司机 {0} ,已存在 {1} 序号为 {2} 的 {3}中", this.GetUserViewNameByID(moniDriverTwo._userId), GetTeamName(moniDriverTwo._team.ToString()), moniDriverTwo._dcomNO.ToString(), monTwoDuty);
                }
            }
            else if (null != moniDriver)
            {
                mess += string.Format("副司机 {0} ,已存在 {1} 序号为 {2} 的 {3}中", this.GetUserViewNameByID(moniDriver._userId), GetTeamName(moniDriver._team.ToString()), moniDriver._dcomNO, monDuty);
                if (null != moniDriverTwo)
                {
                    mess += "\n";
                    mess += string.Format("副司机 {0} ,已存在 {1} 序号为 {2} 的 {3}中", this.GetUserViewNameByID(moniDriverTwo._userId), GetTeamName(moniDriverTwo._team.ToString()), moniDriverTwo._dcomNO.ToString(), monTwoDuty);
                }
            }
            else if (null != moniDriverTwo)
            {
                mess += string.Format("副司机 {0} ,已存在 {1} 序号为 {2} 的 {3}中", this.GetUserViewNameByID(moniDriverTwo._userId), GetTeamName(moniDriverTwo._team.ToString()), moniDriverTwo._dcomNO.ToString(), monTwoDuty);
            }

            return mess;
        }


        //private void AddDriverGroup1()
        //{
        //    //if (cob_opDriver.SelectedIndex < 0 || cob_moniDriver.SelectedIndex < 0)
        //    //{
        //    //    MessageBox.Show("请选择主控或副司机", "插入失败");
        //    //    return;
        //    //}
        //    if (TeamList != null)
        //    {
        //        if (TeamList[teamID - 1].Length >= gridList.RowDefinitions.Count - 1)
        //        {
        //            MessageBox.Show("当前每车队最大允许组合超出范围，如需扩展，请与工作人员联系", "操作失败"); return;
        //        }
        //    }

        //    bool lastAdd = true;
        //    int index = Convert.ToInt32(cob_Index.SelectedValue);
        //    if (cob_opDriver.SelectedItem == null && !string.IsNullOrEmpty(cob_opDriver.Text))
        //    {
        //        MessageBox.Show("主司机信息未录入系统！");
        //        return;
        //    }
        //    if (cob_moniDriver.SelectedItem == null && !string.IsNullOrEmpty(cob_moniDriver.Text))
        //    {
        //        MessageBox.Show("主司机信息未录入系统！");
        //        return;
        //    }
        //    string[] opDriver = cob_opDriver.SelectedItem.ToString().Split(' ');
        //    string[] moniDriver = cob_moniDriver.SelectedItem.ToString().Split(' ');

        //    DriverIn opDriverIn = null;
        //    DriverIn moniDriverIn = null;

        //    int opID = GetIDByUserName(opDriver[1]);
        //    int moniId = GetIDByUserName(moniDriver[1]);

        //    if (ISDriverIn(opID, out opDriverIn) || ISDriverIn(moniId, out moniDriverIn))
        //    {
        //        MessageBoxHelper.ShowTips("主控或副司机已被分组，不能插入到新的分组中！\n若要对分组进行修改，请在操作类型中选择【修改】");
        //        return;
        //    }
        //    if (TeamList != null)
        //    {
        //        if (index <= TeamList[teamID - 1].Length)
        //        {
        //            string update = "update DriverCombine set dcom_dutynum = dcom_dutynum +1 where dcom_team =" + teamID + " and dcom_date is null and  dcom_dutynum >=" + index + "and dcom_lineid = " + lineid;
        //            sqlHelper.ExecuteSql(update);
        //            lastAdd = false;
        //        }
        //    }

        //    string strSql = "insert into DriverCombine(dcom_lineid,dcom_team,dcom_dutynum,dcom_opdriver,dcom_monidriver,dcom_grp_type) values(" + lineid + "," + teamID + "," + index + ",'" + opID + "','" + moniId + "',5);select @@IDENTITY";
        //    int newID = -1;
        //    try
        //    {
        //        newID = Convert.ToInt32(sqlHelper.GetSingle(strSql));
        //    }
        //    catch (System.Exception ex)
        //    {

        //    }

        //    if (newID != -1)
        //    {
        //        MessageBox.Show("插入司机分组成功", "操作成功");
        //        RefreshIndexComboBox();
        //        if (lastAdd)
        //        {
        //            RefreshUIList(newID, index, opDriver[0], moniDriver[0], true);
        //        }
        //        else
        //        {
        //            RefreshUIListMidAdd(index);
        //        }
        //    }
        //    else { MessageBox.Show("插入司机分组失败！", "操作成功"); }
        //}



        private void AddDriverGroup()
        {
            if (cob_cb_lunban.IsChecked.Value)
            {
                MessageBox.Show("添加司机组必须重新手动轮班", "操作失败"); return;
            }
            if (TeamList != null)
            {
                gridList.RowDefinitions.Add(new RowDefinition());
                if (TeamList[teamID - 1].Length >= gridList.RowDefinitions.Count - 1)
                {
                    MessageBox.Show("当前每车队最大允许组合超出范围，如需扩展，请与工作人员联系", "操作失败"); return;
                }
            }
            int index = Convert.ToInt32(cob_Index.SelectedValue);

            if (cob_opDriver.SelectedItem == null && cob_moniDriver.SelectedItem == null && cob_moniDriverTwo.SelectedItem == null && cob_moniDriverThree.SelectedItem == null)
            {
                MessageBox.Show("不能插入空的分组");
                return;
            }

            if (cob_opDriver.SelectedItem == null && !string.IsNullOrEmpty(cob_opDriver.Text))
            {
                MessageBox.Show("主司机信息未录入系统！");
                return;
            }
            if (cob_moniDriver.SelectedItem == null && !string.IsNullOrEmpty(cob_moniDriver.Text))
            {
                MessageBox.Show("副司机信息未录入系统！");
                return;
            }
            if (cob_moniDriverTwo.SelectedItem == null && !string.IsNullOrEmpty(cob_moniDriverTwo.Text))
            {
                MessageBox.Show("副司机信息未录入系统！");
                return;
            }
            if (cob_moniDriverThree.SelectedItem == null && !string.IsNullOrEmpty(cob_moniDriverThree.Text))
            {
                MessageBox.Show("副司机信息未录入系统！");
                return;
            }
            //bool lastAdd = true;
            if (TeamList != null)
            {
                if (index <= TeamList[teamID - 1].Length)
                {
                    string update = "update DriverCombine set dcom_NO = dcom_NO +1 where dcom_team =" + teamID + " and dcom_date is null and  dcom_NO >=" + index + "and dcom_lineid = " + lineid;
                    sqlHelper.ExecuteSql(update);
                    //lastAdd = false;
                }
            }
            string strInsert = "insert into DriverCombine(dcom_lineid,dcom_team,dcom_dutynum,dcom_NO";

            string strVal = "values('" + lineid + "','" + teamID + "','" + (TeamList[teamID-1].Length+1) + "','" + index + "'";
            string refreshopDriver = "";
            if (cob_opDriver.SelectedItem != null)
            {
                strInsert = strInsert + ",dcom_opdriver";
                string[] opDriver = cob_opDriver.SelectedItem.ToString().Split(' ');
                refreshopDriver = opDriver[0];
                strVal = strVal + "," + GetIDByUserName(opDriver[1]);

            }
            string refreshmoniDriver = "";
            if (cob_moniDriver.SelectedItem != null)
            {
                strInsert = strInsert + ",dcom_monidriver";
                string[] moniDriver = cob_moniDriver.SelectedItem.ToString().Split(' ');
                refreshmoniDriver = moniDriver[0];
                strVal = strVal + "," + GetIDByUserName(moniDriver[1]);

            }

            string refreshmoniDriverTwo = "";
            if (cob_moniDriverTwo.SelectedItem != null)
            {
                strInsert = strInsert + ",dcom_monidriverTwo";
                string[] moniDriverTwo = cob_moniDriverTwo.SelectedItem.ToString().Split(' ');
                refreshmoniDriverTwo = moniDriverTwo[0];
                strVal = strVal + "," + GetIDByUserName(moniDriverTwo[1]);

            }
            string refreshmoniDriverThree = "";
            if (cob_moniDriverThree.SelectedItem != null)
            {
                strInsert = strInsert + ",dcom_monidriverThree";
                string[] moniDriverThree = cob_moniDriverThree.SelectedItem.ToString().Split(' ');
                refreshmoniDriverThree = moniDriverThree[0];
                strVal = strVal + "," + GetIDByUserName(moniDriverThree[1]);

            }

            strInsert = strInsert + ",dcom_grp_type)";
            strVal = strVal + ",5);select @@IDENTITY";
            strInsert = strInsert + strVal;
            int newID = -1;
            //string sortSql = "update DriverCombine set ";

            try
            {
                newID = Convert.ToInt32(sqlHelper.GetSingle(strInsert));
            }
            catch (System.Exception ex)
            {

            }
            
            if (newID != -1)
            {
                MessageBox.Show("插入司机分组成功", "操作成功");

                //if (cob_cb_lunban.IsChecked.Value)
                //{
                    //DataTable dcdt = sqlHelper.SelectDt("select dc.*,s1.user_view_name as dcom_opdriverName,s2.user_view_name as dcom_monidriverName,s3.user_view_name as dcom_monidriverNameTwo from DriverCombine as dc " +
                    //    " left join [system_user] as s1 on s1.user_id=dc.dcom_opdriver left join [system_user] as s2 on s2.user_id=dc.dcom_monidriver "+
                    //    " left join [system_user] as s3 on s3.user_id=dc.dcom_monidriverTwo "+
                    //    " where id=" + newID);
                    //DataRow dcrow = dcdt.Rows[0];
                    //string lunbanSql = "";
                    //if (dcrow["dcom_opdriver"] != DBNull.Value)
                    //{
                    //    lunbanSql+=
                    //}
                //}
                
                

                InitTeamList();
                InitDriverGroupList();
                //RefreshIndexComboBox();
                //RefreshUIList(newID, index, refreshopDriver, refreshmoniDriver, refreshmoniDriverTwo, true);

            }
            else { MessageBox.Show("插入司机分组失败！", "操作成功"); }
        }
        public ArrayList GetUpdateDutyNumAndNoScript(int teamId, int dutyNum, int no) {
            string update = "update DriverCombine set dcom_no = dcom_no -1 where dcom_team =" + teamId + " and dcom_date is null and dcom_no >" + no + " and dcom_lineid = " + lineid + ";";
            string updateDutyNum = "update DriverCombine set dcom_dutynum = dcom_dutynum -1 where dcom_team =" + teamId + " and dcom_date is null and dcom_dutynum >" + dutyNum + " and dcom_lineid = " + lineid + ";";
            ArrayList strlist = new ArrayList();
            strlist.Add(update);
            strlist.Add(updateDutyNum);
            return strlist;
        }
        /// <summary>
        /// 当司机组中间被删除时，更新dutynum和no列
        /// </summary>
        /// <param name="teamID"></param>
        /// <param name="dutyNum"></param>
        /// <param name="no"></param>
        public void UpdateDutyNumAndNo(int teamID,int dutyNum,int no)
        {
            sqlHelper.ExecuteSqlTran(GetUpdateDutyNumAndNoScript(teamID, dutyNum, no));
        }
        private void DeleteDriverGroup1() {

            if (cob_cb_lunban.IsChecked.Value)
            {
                MessageBoxHelper.ShowTips("不能删除，删除必须手动轮班");
                return;
            }

            int index = cob_Index.SelectedIndex + 1;

            if (cob_cb_lunban.IsChecked.Value)
            {
                if (!MessageBoxHelper.ConfirmYesNo("删除必须要手动轮班，要继续删除吗？"))
                    return;
            }

            if (index > TeamList[teamID - 1].Length)
            {
                MessageBox.Show("请确认队伍的序号存在后再执行删除操作！", "操作失败"); return;
            }
            //通过index 查找出对应的司机组轮值序号
            var old = index;
            index = GetIndexByNO(index);
            string strSql = "delete from DriverCombine where dcom_team =" + teamID + " and dcom_date is null and dcom_dutynum = " + index + " and dcom_lineid = " + lineid;
            if (sqlHelper.ExecuteSql(strSql) == 1)
            {
                MessageBoxHelper.ShowTips(string.Format("删除电客车{0}队 序号{1}的司机组合成功！", teamID, old));
                UpdateDutyNumAndNo(teamID, index, old);

                RefreshIndexComboBox();
                RefreshUIListDelete(index);
                InitTeamList();
                InitDriverGroupList();
            }
        }
        private void DeleteDriverGroup()
        {

            if (cob_cb_lunban.IsChecked.Value)
            {
                MessageBoxHelper.ShowTips("不能删除，删除必须手动轮班");
                return;
            }

            int index = cob_Index.SelectedIndex + 1;

            if (cob_cb_lunban.IsChecked.Value) {
                if (!MessageBoxHelper.ConfirmYesNo("删除必须要手动轮班，要继续删除吗？"))
                    return;
            }
            
            if (index > TeamList[teamID - 1].Length)
            {
                MessageBox.Show("请确认队伍的序号存在后再执行删除操作！", "操作失败"); return;
            }
            //通过index 查找出对应的司机组轮值序号
            var old = index;
            index = GetIndexByNO(index);

            //都没有选 || 都选中 ||有其中两个没有
            if ((cob_moniDriver.SelectedIndex * cob_opDriver.SelectedIndex * cob_moniDriverTwo.SelectedIndex*cob_moniDriverThree.SelectedIndex < 0) ||
                (cob_moniDriver.SelectedIndex >= 0 && cob_opDriver.SelectedIndex >= 0 && cob_moniDriverTwo.SelectedIndex >= 0&&cob_moniDriverThree.SelectedIndex>=0) ||
               ((cob_opDriver.Items.Count == 0 && cob_moniDriver.Items.Count == 0) || (cob_opDriver.Items.Count == 0 && cob_moniDriverTwo.Items.Count == 0) ||
               (cob_moniDriver.Items.Count == 0 && cob_moniDriverTwo.Items.Count == 0)))
            {
                string strSql = "delete from DriverCombine where dcom_team =" + teamID + " and dcom_date is null and dcom_dutynum = " + index + " and dcom_lineid = " + lineid;
                if (sqlHelper.ExecuteSql(strSql) == 1)
                {
                    MessageBoxHelper.ShowTips(string.Format("删除电客车{0}队 序号{1}的司机组合成功！", teamID, old));
                    UpdateDutyNumAndNo(teamID, index, old);

                    RefreshIndexComboBox();
                    RefreshUIListDelete(index);
                    InitTeamList();
                    InitDriverGroupList();
                }
            }
            //选A，不选B、C，A代表主司机，B、C分别代表副司机1、2
            else if (cob_opDriver.SelectedIndex >= 0 && (cob_moniDriver.SelectedIndex * cob_moniDriverTwo.SelectedIndex > 0))
            {
                //删除主司机
                string strDelOp = string.Format("update DriverCombine set dcom_opdriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", teamID, index, lineid);
                if (sqlHelper.ExecuteSql(strDelOp) == 1)
                {

                    MessageBoxHelper.ShowTips(string.Format("删除电客车{0}队 序号为{1}的主司机成功！", GetTeamName(teamID.ToString()), index));
                    RefreshIndexComboBox();
                    InitDriverGroupList();
                }


            }
            //选A、B，不选C
            else if (cob_opDriver.SelectedIndex >= 0 && cob_moniDriver.SelectedIndex >= 0 && cob_moniDriverTwo.SelectedIndex < 0)
            {
                //删除主司机、副司机1

                string strDelOp = string.Format("update DriverCombine set dcom_opdriver = null, dcom_monidriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", teamID, index, lineid);
                if (sqlHelper.ExecuteSql(strDelOp) == 1)
                {

                    MessageBoxHelper.ShowTips(string.Format("删除电客车{0}队 序号为{1}的主、副司机1成功！", GetTeamName(teamID.ToString()), index));
                    RefreshIndexComboBox();
                    InitDriverGroupList();
                }
            }
            //选A、C，不选B
            else if (cob_opDriver.SelectedIndex >= 0 && cob_moniDriverTwo.SelectedIndex >= 0 && cob_moniDriver.SelectedIndex < 0)
            {
                //删除主司机、副司机2

                string strDelOp = string.Format("update DriverCombine set dcom_opdriver = null, dcom_monidriverTwo = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", teamID, index, lineid);
                if (sqlHelper.ExecuteSql(strDelOp) == 1)
                {

                    MessageBoxHelper.ShowTips(string.Format("删除电客车{0}队 序号为{1}的主、副2司机成功！", GetTeamName(teamID.ToString()), index));
                    RefreshIndexComboBox();
                    InitDriverGroupList();
                }
            }
            //选B，不选A、C
            else if (cob_moniDriver.SelectedIndex >= 0 && cob_opDriver.SelectedIndex * cob_moniDriverTwo.SelectedIndex > 0)
            {
                //删除副司机1
                string strDelOp = string.Format("update DriverCombine set dcom_monidriver = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", teamID, index, lineid);
                if (sqlHelper.ExecuteSql(strDelOp) == 1)
                {

                    MessageBoxHelper.ShowTips(string.Format("删除电客车{0}队 序号为{1}的副司机1成功！", GetTeamName(teamID.ToString()), index));
                    RefreshIndexComboBox();
                    InitDriverGroupList();
                }
            }
            //选BC，不选A
            else if (cob_moniDriver.SelectedIndex >= 0 && cob_moniDriverTwo.SelectedIndex >= 0 && cob_opDriver.SelectedIndex < 0)
            {
                //删除副司机1、2
                string strDelOp = string.Format("update DriverCombine set dcom_monidriver = null, dcom_monidriverTwo = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", teamID, index, lineid);
                if (sqlHelper.ExecuteSql(strDelOp) == 1)
                {

                    MessageBoxHelper.ShowTips(string.Format("删除电客车{0}队 序号为{1}的副司机1、2成功！", GetTeamName(teamID.ToString()), index));
                    RefreshIndexComboBox();
                    InitDriverGroupList();
                }
            }
            //选C，不选A、B
            else if (cob_moniDriverTwo.SelectedIndex >= 0 && cob_opDriver.SelectedIndex * cob_moniDriver.SelectedIndex > 0)
            {
                //删除副司机2
                string strDelOp = string.Format("update DriverCombine set dcom_monidriverTwo = null where dcom_team = {0} and dcom_dutynum = {1} and dcom_lineid = {2} and dcom_date is null", teamID, index, lineid);
                if (sqlHelper.ExecuteSql(strDelOp) == 1)
                {

                    MessageBoxHelper.ShowTips(string.Format("删除电客车{0}队 序号为{1}的副司机2成功！", GetTeamName(teamID.ToString()), index));
                    RefreshIndexComboBox();
                    InitDriverGroupList();
                }
            }
        }

        /// <summary>
        /// 通过序号查找轮值序号
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public int GetIndexByNO(int index)
        {
            string strSqlNO = "select dcom_dutynum from DriverCombine where dcom_NO = '" + index + "' and dcom_date is null and dcom_team='"+teamID+"' and dcom_lineid='" + lineid + "'";
            DataTable dt=sqlHelper.SelectDt(strSqlNO);
            if (dt.Rows.Count > 0)
            {
                return Convert.ToInt32(dt.Rows[0]["dcom_dutynum"].ToString());
            }
            else
            {
                return -1;
            }
        }

        /// <summary>
        /// 检查司机是否已经有分组
        /// </summary>
        /// <param name="num">工号</param>
        /// <returns></returns>
        //private bool ISDriverIn(int num, out DriverIn driverIn)
        //{
        //    driverIn = null;
        //    if (num < 1)
        //        return false;

        //    // string strSql = "select dcom_team,dcom_dutynum,dcom_opdriver,dcom_monidriver from DriverCombine where dcom_opdriver = '" + num + "' or dcom_monidriver = '" + num + "'";
        //    string strSqlOpdriver = "select dcom_team,dcom_dutynum,dcom_opdriver,dcom_monidriver from DriverCombine where dcom_opdriver = '" + num + "' and dcom_date is null";
        //    string strSqlMonidriver = "select dcom_team,dcom_dutynum,dcom_opdriver,dcom_monidriver from DriverCombine where dcom_monidriver = '" + num + "' and dcom_date is null";
        //    string strSqlMonidriverTwo = "select dcom_team,dcom_dutynum,dcom_opdriver,dcom_monidriver, dcom_monidriverTwo from DriverCombine where dcom_monidriver = '" + num + "' and dcom_date is null";
    

        //    //int count = Convert.ToInt32(sqlHelper.GetSingle(strSql));
        //    DataTable dtOpdriver = sqlHelper.SelectDt(strSqlOpdriver);
        //    DataTable dtMonidriver = sqlHelper.SelectDt(strSqlMonidriver);
        //    DataTable dtMonidriverTwo = sqlHelper.SelectDt(strSqlMonidriverTwo);

        //    if (dtOpdriver.Rows.Count < 1 && dtMonidriver.Rows.Count < 1 && dtMonidriverTwo.Rows.Count < 1)
        //    {
        //        return false;
        //    }

        //    if (dtOpdriver.Rows.Count > 0)
        //    {
        //        driverIn = new DriverIn(num, Convert.ToInt32(dtOpdriver.Rows[0]["dcom_team"]), Convert.ToInt32(dtOpdriver.Rows[0]["dcom_dutynum"]), "Opdriver", dtOpdriver.Rows[0]["dcom_opdriver"].ToString(), dtOpdriver.Rows[0]["dcom_monidriver"].ToString(), dtOpdriver.Rows[0]["dcom_monidriverTwo"].ToString());
        //        return true;
        //    }

        //    if (dtMonidriver.Rows.Count > 0)
        //    {
        //        driverIn = new DriverIn(num, Convert.ToInt32(dtMonidriver.Rows[0]["dcom_team"]), Convert.ToInt32(dtMonidriver.Rows[0]["dcom_dutynum"]), "Monidriver", dtMonidriver.Rows[0]["dcom_opdriver"].ToString(), dtMonidriver.Rows[0]["dcom_monidriver"].ToString(), dtMonidriver.Rows[0]["dcom_monidriverTwo"].ToString());
        //        return true;
        //    }
        //    if (dtMonidriverTwo.Rows.Count > 0)
        //    {
        //        driverIn = new DriverIn(num, Convert.ToInt32(dtMonidriverTwo.Rows[0]["dcom_team"]), Convert.ToInt32(dtMonidriverTwo.Rows[0]["dcom_dutynum"]), "Monidriver", dtMonidriverTwo.Rows[0]["dcom_opdriver"].ToString(), dtMonidriverTwo.Rows[0]["dcom_monidriver"].ToString(), dtMonidriverTwo.Rows[0]["dcom_monidriverTwo"].ToString());
        //        return true;
        //    }
        //    //if (null == dt || dt.Rows.Count < 1)
        //    //{
        //    //    return false;
        //    //}

        //    //driverIn = new DriverIn(num, Convert.ToInt32(dt.Rows[0]["dcom_team"]), Convert.ToInt32(dt.Rows[0]["dcom_dutynum"]));

        //    return true;
        //}

        private bool ISDriverIn(int num, out DriverIn driverIn, string teamid, string index, string type)
        {
            driverIn = null;
            if (num < 1)
                return false;

            // string strSql = "select dcom_team,dcom_dutynum,dcom_opdriver,dcom_monidriver from DriverCombine where dcom_opdriver = '" + num + "' or dcom_monidriver = '" + num + "'";
            string strSqlOpdriver = "select dcom_team,dcom_dutynum,dcom_opdriver,dcom_monidriver,dcom_monidriverTwo,dcom_NO,dcom_monidriverThree from DriverCombine where dcom_opdriver = '" + num + "' and dcom_date is null";

            string strSqlMonidriver = "select dcom_team,dcom_dutynum,dcom_opdriver,dcom_monidriver,dcom_monidriverTwo,dcom_NO,dcom_monidriverThree from DriverCombine where dcom_monidriver = '" + num + "' and dcom_date is null";

            string strSqlMonidriverTwo = "select dcom_team,dcom_dutynum,dcom_opdriver,dcom_monidriver,dcom_monidriverTwo,dcom_NO,dcom_monidriverThree from DriverCombine where dcom_monidriverTwo = '" + num + "' and dcom_date is null";

            string strSqlMonidriverThree = "select dcom_team,dcom_dutynum,dcom_opdriver,dcom_monidriver,dcom_monidriverTwo,dcom_NO,dcom_monidriverThree from DriverCombine where dcom_monidriverThree = '" + num + "' and dcom_date is null";
            //int count = Convert.ToInt32(sqlHelper.GetSingle(strSql));
            DataTable dtOpdriver = sqlHelper.SelectDt(strSqlOpdriver);
            DataTable dtMonidriver = sqlHelper.SelectDt(strSqlMonidriver);
            DataTable dtMonidriverTwo = sqlHelper.SelectDt(strSqlMonidriverTwo);
            DataTable dtMonidriverThree = sqlHelper.SelectDt(strSqlMonidriverThree);
            if (dtOpdriver.Rows.Count < 1 && dtMonidriver.Rows.Count < 1 && dtMonidriverTwo.Rows.Count < 1&&dtMonidriverThree.Rows.Count<1)
            {
                return false;
            }

            if (dtOpdriver.Rows.Count > 0)
            {
                if (type == "Opdriver" && dtOpdriver.Rows[0]["dcom_team"].ToString().Trim() == teamid && dtOpdriver.Rows[0]["dcom_dutynum"].ToString().Trim() == index)
                {
                    //如果都是主司机的位置 判断是不是在同一个位置
                    return false;
                }
                else
                {
                    driverIn = new DriverIn(num, Convert.ToInt32(dtOpdriver.Rows[0]["dcom_team"]), 
                        Convert.ToInt32(dtOpdriver.Rows[0]["dcom_dutynum"]), "Opdriver", dtOpdriver.Rows[0]["dcom_opdriver"].ToString(),
                        dtOpdriver.Rows[0]["dcom_monidriver"].ToString(), dtOpdriver.Rows[0]["dcom_monidriverTwo"].ToString(), dtOpdriver.Rows[0]["dcom_monidriverThree"].ToString(), Convert.ToInt32(dtOpdriver.Rows[0]["dcom_no"]));
                }
                return true;
            }

            if (dtMonidriver.Rows.Count > 0)
            {
                if (type == "Monidriver" && dtMonidriver.Rows[0]["dcom_team"].ToString().Trim() == teamid && dtMonidriver.Rows[0]["dcom_dutynum"].ToString().Trim() == index)
                {
                    //如果都监控的位置 判断是不是在同一个位置
                    return false;
                }
                else
                {
                    driverIn = new DriverIn(num, Convert.ToInt32(dtMonidriver.Rows[0]["dcom_team"]), 
                        Convert.ToInt32(dtMonidriver.Rows[0]["dcom_dutynum"]), "Monidriver", dtMonidriver.Rows[0]["dcom_opdriver"].ToString(),
                        dtMonidriver.Rows[0]["dcom_monidriver"].ToString(), dtMonidriver.Rows[0]["dcom_monidriverTwo"].ToString(), dtMonidriver.Rows[0]["dcom_monidriverThree"].ToString(), Convert.ToInt32(dtMonidriver.Rows[0]["dcom_no"]));
                }
                return true;
            }
            if (dtMonidriverTwo.Rows.Count > 0)
            {
                if (type == "MonidriverTwo" && dtMonidriverTwo.Rows[0]["dcom_team"].ToString().Trim() == teamid && dtMonidriverTwo.Rows[0]["dcom_dutynum"].ToString().Trim() == index)
                {
                    //如果都监控的位置 判断是不是在同一个位置
                    return false;
                }
                else
                {
                    driverIn = new DriverIn(num, Convert.ToInt32(dtMonidriverTwo.Rows[0]["dcom_team"]), 
                        Convert.ToInt32(dtMonidriverTwo.Rows[0]["dcom_dutynum"]), "MonidriverTwo", dtMonidriverTwo.Rows[0]["dcom_monidriverTwo"].ToString(),
                        dtMonidriverTwo.Rows[0]["dcom_monidriverTwo"].ToString(), dtMonidriverTwo.Rows[0]["dcom_monidriverTwo"].ToString(), dtMonidriverTwo.Rows[0]["dcom_monidriverThree"].ToString(), Convert.ToInt32(dtMonidriverTwo.Rows[0]["dcom_no"]));
                }
                return true;
            }
            if (dtMonidriverThree.Rows.Count > 0)
            {
                if (type == "MonidriverThree" && dtMonidriverThree.Rows[0]["dcom_team"].ToString().Trim() == teamid && dtMonidriverThree.Rows[0]["dcom_dutynum"].ToString().Trim() == index)
                {
                    //如果都监控的位置 判断是不是在同一个位置
                    return false;
                }
                else
                {
                    driverIn = new DriverIn(num, Convert.ToInt32(dtMonidriverThree.Rows[0]["dcom_team"]),
                        Convert.ToInt32(dtMonidriverThree.Rows[0]["dcom_dutynum"]), "MonidriverThree", dtMonidriverThree.Rows[0]["dcom_monidriverTwo"].ToString(),
                        dtMonidriverThree.Rows[0]["dcom_monidriverTwo"].ToString(), dtMonidriverThree.Rows[0]["dcom_monidriverTwo"].ToString(),dtMonidriverThree.Rows[0]["dcom_monidriverThree"].ToString(), Convert.ToInt32(dtMonidriverThree.Rows[0]["dcom_no"]));
                }
                return true;
            }
            //if (null == dt || dt.Rows.Count < 1)
            //{
            //    return false;
            //}

            //driverIn = new DriverIn(num, Convert.ToInt32(dt.Rows[0]["dcom_team"]), Convert.ToInt32(dt.Rows[0]["dcom_dutynum"]));

            return true;
        }

        private int GetIDByUserName(string userName)
        {
            int result = -1;

            foreach (KeyValuePair<int, Driver> kvp in DicDriverInfo)
            {
                if (kvp.Value.userName == userName)
                {
                    result = kvp.Key;
                    break;
                }
            }

            return result;
        }

        private int GetIDByUserViewName(string userViewName)
        {
            int result = -1;

            foreach (KeyValuePair<int, Driver> kvp in DicDriverInfo)
            {
                if (kvp.Value.userViewName == userViewName)
                {
                    result = kvp.Key;
                    break;
                }
            }
            if (result == -1)
            {
                int i;
            }
            return result;
        }

        public string GetUserViewNameByID(int ID)
        {
            string result = "";
            Driver driver = null;
            if (DicDriverInfo.TryGetValue(ID, out driver))
            {
                result = driver.userViewName;
            }

            return result;
        }

        private string GetUserNameByID(int ID)
        {
            string result = "";
            foreach (KeyValuePair<int, Driver> kvp in DicDriverInfo)
            {
                if (kvp.Key == ID)
                {
                    result = kvp.Value.userName;
                    break;
                }
            }

            return result;
        }

        private void RefreshIndexComboBox()
        {
            InitTeamList();
            ReInitIndexList(teamID);
        }

        private void RefreshUIList(int ID, int index, string opName, string moniName, bool isNew)
        {
            string itemName = "item" + teamID.ToString() + index.ToString();
            object ob;
            DriverGroupCombine UIElem;
            try
            {
                ob = LogicalTreeHelper.FindLogicalNode(gridList, itemName);
                if (ob == null)
                {
                    UIElem = new DriverGroupCombine(index);

                    UIElem.Name = itemName;
                    Grid.SetColumn(UIElem, teamID - 1);
                    Grid.SetRow(UIElem, index);
                    gridList.Children.Add(UIElem);
                }
                else { UIElem = ob as DriverGroupCombine; }
                if (isNew)
                {
                    UIElem.ID = ID.ToString();
                }
                UIElem.Index = index.ToString();
                UIElem.OperateDriver = opName;
                UIElem.MonitorDriver = moniName;
                UIElem.InitColor();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("找不到指定控件名称！ " + ex.Message.ToString());
            }
        }

        private void RefreshUIList(int ID, int index, string opName, string moniName, string moniNameTwo, bool isNew)
        {
            string itemName = "item" + teamID.ToString() + index.ToString();
            object ob;
            DriverGroupCombine UIElem;
            try
            {
                ob = LogicalTreeHelper.FindLogicalNode(gridList, itemName);
                if (ob == null)
                {
                    UIElem = new DriverGroupCombine(index);

                    UIElem.Name = itemName;
                    Grid.SetColumn(UIElem, teamID - 1);
                    Grid.SetRow(UIElem, index);
                    gridList.Children.Add(UIElem);
                }
                else { UIElem = ob as DriverGroupCombine; }
                if (isNew)
                {
                    UIElem.ID = ID.ToString();
                }
                UIElem.Index = index.ToString();
                UIElem.OperateDriver = opName;
                UIElem.MonitorDriver = moniName;
                UIElem.MonitorDriverTwo = moniNameTwo;
                UIElem.InitColor();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("找不到指定控件名称！ " + ex.Message.ToString());
            }
        }


        private void RefreshUIList(int teamID, int index, string Name, bool IsOp)
        {
            string itemName = "item" + teamID.ToString() + index.ToString();
            DriverGroupCombine UIElem;
            try
            {
                UIElem = LogicalTreeHelper.FindLogicalNode(gridList, itemName) as DriverGroupCombine;

                UIElem.Index = index.ToString();
                if (IsOp)
                {
                    UIElem.OperateDriver = Name;
                }
                else
                {
                    UIElem.MonitorDriver = Name;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("找不到指定控件名称！ " + ex.Message.ToString());
            }
        }

        private void RefreshUIListMidAdd(int startIndex)
        {
            //InitTeamList();
            string itemName;
            int teamIndex = teamID - 1;
            for (; startIndex < TeamList[teamIndex].Length; startIndex++)
            {
                itemName = "item" + teamID.ToString() + startIndex.ToString();
                try
                {
                    DriverGroupCombine item = LogicalTreeHelper.FindLogicalNode(gridList, itemName) as DriverGroupCombine;
                    if (item == null) { continue; }
                    item.ID = TeamList[teamIndex][startIndex - 1]["ID"].ToString();
                    item.Index = TeamList[teamIndex][startIndex - 1]["dcom_dutynum"].ToString();
                    if (TeamList[teamIndex][startIndex - 1]["dcom_opdriver"].ToString() != "")
                    {
                        item.OperateDriver = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_opdriver"]));
                    }
                    if (TeamList[teamIndex][startIndex - 1]["dcom_monidriver"].ToString() != "")
                    {
                        item.MonitorDriver = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_monidriver"]));
                    }
                    if (TeamList[teamIndex][startIndex - 1]["dcom_monidriverTwo"].ToString() != "")
                    {
                        item.MonitorDriverTwo = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_monidriverTwo"]));
                    }
                    item.Notes = TeamList[teamIndex][startIndex - 1]["grp_type"].ToString();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("更新界面时出现异常，请关闭窗口后重新打开");
                }
            }
            //最后一个特殊处理
            itemName = "item" + teamID.ToString() + TeamList[teamIndex].Length.ToString();
            try
            {
                DriverGroupCombine item = LogicalTreeHelper.FindLogicalNode(gridList, itemName) as DriverGroupCombine;
                if (item == null)
                {
                    item = new DriverGroupCombine(TeamList[teamIndex].Length);
                    item.Name = itemName;
                    Grid.SetRow(item, TeamList[teamIndex].Length);
                    Grid.SetColumn(item, teamIndex);
                    gridList.Children.Add(item);
                }
                item.ID = TeamList[teamIndex][TeamList[teamIndex].Length - 1]["ID"].ToString(); ;
                item.Index = TeamList[teamIndex][TeamList[teamIndex].Length - 1]["dcom_dutynum"].ToString();
                if (TeamList[teamIndex][TeamList[teamIndex].Length - 1]["dcom_opdriver"].ToString() != "")
                {
                    item.OperateDriver = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][TeamList[teamIndex].Length - 1]["dcom_opdriver"]));
                }
                if (TeamList[teamIndex][TeamList[teamIndex].Length - 1]["dcom_monidriver"].ToString() != "")
                {
                    item.MonitorDriver = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][TeamList[teamIndex].Length - 1]["dcom_monidriver"]));
                }
                if (TeamList[teamIndex][TeamList[teamIndex].Length - 1]["dcom_monidriverTwo"].ToString() != "")
                {
                    item.MonitorDriverTwo = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][TeamList[teamIndex].Length - 1]["dcom_monidriverTwo"]));
                }
                item.Notes = TeamList[teamIndex][TeamList[teamIndex].Length - 1]["grp_type"].ToString();
                item.InitColor();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("更新界面时出现异常，请关闭窗口后重新打开");
            }
        }

        private void RefreshUIListDelete(int startIndex)
        {
            //InitTeamList();
            string itemName;
            int teamIndex = teamID - 1;
            for (; startIndex <= TeamList[teamIndex].Length; startIndex++)
            {
                itemName = "item" + teamID.ToString() + startIndex.ToString();
                try
                {
                    DriverGroupCombine item = LogicalTreeHelper.FindLogicalNode(gridList, itemName) as DriverGroupCombine;
                    if (item == null) { continue; }
                    item.ID = TeamList[teamIndex][startIndex - 1]["ID"].ToString();
                    item.Index = TeamList[teamIndex][startIndex - 1]["dcom_dutynum"].ToString();
                    if (TeamList[teamIndex][startIndex - 1]["dcom_opdriver"].ToString() != "")
                    {
                        item.OperateDriver = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_opdriver"]));
                    }
                    if (TeamList[teamIndex][startIndex - 1]["dcom_monidriver"].ToString() != "")
                    {
                        item.MonitorDriver = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_monidriver"]));
                    }
                    //可能有些组合不存在第二个副司机
                    if (TeamList[teamIndex][startIndex - 1]["dcom_monidriverTwo"].ToString() != "")
                    {
                        item.MonitorDriverTwo = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_monidriverTwo"]));
                    }
                    if (TeamList[teamIndex][startIndex - 1]["dcom_monidriverThree"].ToString() != "")
                    {
                        item.MonitorDriverThree = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_monidriverThree"]));
                    }
                    item.Notes = TeamList[teamIndex][startIndex - 1]["grp_type"].ToString();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("更新界面时出现异常，请关闭窗口后重新打开deldel");
                }
            }
            //最后一个特殊处理
            itemName = "item" + teamID.ToString() + (TeamList[teamIndex].Length + 1).ToString();
            try
            {
                DriverGroupCombine item = LogicalTreeHelper.FindLogicalNode(gridList, itemName) as DriverGroupCombine;
                if (null != item)
                {
                    item.ReInit();
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("更新界面时出现异常，请关闭窗口后重新打开");
            }
        }

        private void RefreshUIListDelete(int AteamIndex, int startIndex)
        {
            //InitTeamList();
            string itemName;
            int teamIndex = AteamIndex - 1;
            for (; startIndex <= TeamList[teamIndex].Length; startIndex++)
            {
                itemName = "item" + teamID.ToString() + startIndex.ToString();
                try
                {
                    DriverGroupCombine item = LogicalTreeHelper.FindLogicalNode(gridList, itemName) as DriverGroupCombine;
                    if (item == null) { continue; }
                    item.ID = TeamList[teamIndex][startIndex - 1]["ID"].ToString();
                    item.Index = TeamList[teamIndex][startIndex - 1]["dcom_dutynum"].ToString();
                    item.OperateDriver = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_opdriver"]));
                    item.MonitorDriver = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_monidriver"]));
                    item.MonitorDriverTwo = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_monidriverTwo"]));
                    item.MonitorDriverThree = GetUserViewNameByID(Convert.ToInt32(TeamList[teamIndex][startIndex - 1]["dcom_monidriverThree"]));
                    item.Notes = TeamList[teamIndex][startIndex - 1]["grp_type"].ToString();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("更新界面时出现异常，请关闭窗口后重新打开");
                }
            }
            //最后一个特殊处理
            itemName = "item" + teamID.ToString() + (TeamList[teamIndex].Length + 1).ToString();
            try
            {
                DriverGroupCombine item = LogicalTreeHelper.FindLogicalNode(gridList, itemName) as DriverGroupCombine;
                if (null != item)
                {
                    item.ReInit();
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("更新界面时出现异常，请关闭窗口后重新打开");
            }
        }

        private void btn_editNum_Click(object sender, RoutedEventArgs e)
        {
            if (teamID == -1)
            {
                MessageBox.Show("请选择需要进行修改的电客车队列！", "操作失败");
                return;
            }
            int count = TeamList[teamID - 1].Length;
            string itemName = null;
            for (int i = 0; i < count; i++)
            {
                itemName = "item" + teamID.ToString() + (i + 1).ToString();
                DriverGroupCombine item = LogicalTreeHelper.FindLogicalNode(gridList, itemName) as DriverGroupCombine;
                if (null != item)
                {
                    item.SetTbEditable(true);
                }
            }
            this.cob_team.IsEnabled = false;
            this.btn_editNum.IsEnabled = false;
            this.btn_confirm.IsEnabled = false;

            this.btn_Save.IsEnabled = true;
        }

        private void btn_Save_Click(object sender, RoutedEventArgs e)
        {
            if (teamID == -1)
            {
                MessageBoxHelper.ShowError("请选择电客车组");
            }
            else
            {
                int count = TeamList[teamID - 1].Length;
                string itemName = null;
                string sql_update;
                ArrayList sqlList = new ArrayList();
                ArrayList items = new ArrayList();  //用来成功保存后修改 TextBox的 readonly 属性
                initCheckDic(count);
                bool hasNum = false;
                try
                {
                    for (int i = 0; i < count; i++)
                    {
                        itemName = "item" + teamID.ToString() + (i + 1).ToString();
                        DriverGroupCombine item = LogicalTreeHelper.FindLogicalNode(gridList, itemName) as DriverGroupCombine;
                        if (null != item)
                        {
                            if (string.IsNullOrEmpty(item.ID))
                            {
                                continue;
                            }
                            int index = Convert.ToInt32(item.Index);
                            if (CheckIndexSingle.TryGetValue(index, out hasNum))
                            {
                                if (!hasNum)    //false表示该值还没被占用
                                {
                                    CheckIndexSingle[index] = true;

                                    items.Add(item);
                                    sql_update = "update DriverCombine set dcom_NO = '" + index + "' where ID = '" + item.ID + "' and dcom_date is null";

                                    sqlList.Add(sql_update);
                                }
                                else { MessageBoxHelper.ShowError(string.Format("序号:{0} 出现了重复，请确认出勤序号的唯一性后点击保存", index)); return; }
                            }
                            else
                            {
                                MessageBoxHelper.ShowError(string.Format("电客车{0}组的值轮序号范围在 1 ~ {1},请确认序号无误后重新保存", teamID, count));
                                return;
                            }
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBoxHelper.ShowError(string.Format("保存失败！Error ：{0}", ex.Message));
                    return;
                }

                if (sqlHelper.ExecuteSqlTran(sqlList))
                {
                    MessageBoxHelper.ShowTips(string.Format("保存电客车{0}组值轮序号修改成功！", teamID));

                    InitTeamList();
                    InitDriverGroupList();
                }
                else
                    MessageBoxHelper.ShowError("保存失败！请确认无误后重试！");

                foreach (DriverGroupCombine item in items)         //改变属性为不可编辑
                {
                    item.SetTbEditable(false);
                }

                this.cob_team.IsEnabled = true;
                this.btn_editNum.IsEnabled = true;
                this.btn_confirm.IsEnabled = true;

                this.btn_Save.IsEnabled = false;
            }
        }

        private void initCheckDic(int count)
        {
            CheckIndexSingle = new Dictionary<int, bool>(count);
            for (int i = 1; i <= count; i++)
            {
                CheckIndexSingle.Add(i, false);
            }
        }

        /// <summary>
        /// 选中序号的绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cob_Index_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //删除的时候绑定
            if (Action == 2)
            {
                //删除只显示同组的司机
                InitDriverComboBoxDel();
            }


            //添加
            if (Action == 1)
            {
                InitDriverComBoxByAdd();
            }
            //修改
            if (Action == 0)
            {
                if (this.cob_Index.SelectedIndex == -1)
                {
                    return;
                }
                int index =Convert.ToInt32(cob_Index.SelectedValue);
                index = GetIndexByNO(index);
                string opDriver = "";
                string moniDriver = "";
                string moniDriverTwo = "";
                string moniDriverThree = "";
                string sql = "select * from DriverCombine where dcom_team = '" + teamID + "' and dcom_date is null and dcom_dutynum='" + index + "' and dcom_lineid='" + lineid + "'";
                DataTable dt = sqlHelper.SelectDt(sql);
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["dcom_opdriver"].ToString() != "")
                    {
                        int opID = Convert.ToInt32(dt.Rows[0]["dcom_opdriver"].ToString());
                        opDriver = GetUserViewNameByID(opID) + " " + GetUserNameByID(opID);

                        //for (int i = 0; i < DriverList.Count; i++)
                        //{
                        //    if (GetUserViewNameByID(opID) == DriverList[i].Split(' ')[0])
                        //    {
                        //        this.cob_opDriver.Text = DriverList[i].ToString();
                        //    }
                        //}

                    }
                    if (dt.Rows[0]["dcom_monidriver"].ToString() != "")
                    {
                        int moniID = Convert.ToInt32(dt.Rows[0]["dcom_monidriver"].ToString());
                        moniDriver = GetUserViewNameByID(moniID) + " " + GetUserNameByID(moniID);

                    }
                    if (dt.Rows[0]["dcom_monidriverTwo"].ToString() != "")
                    {
                        int moniTwoID = Convert.ToInt32(dt.Rows[0]["dcom_monidriverTwo"].ToString());
                        moniDriverTwo = GetUserViewNameByID(moniTwoID) + " " + GetUserNameByID(moniTwoID);

                    }
                    if (dt.Rows[0]["dcom_monidriverThree"].ToString() != "")
                    {
                        int moniThreeID = Convert.ToInt32(dt.Rows[0]["dcom_monidriverThree"].ToString());
                        moniDriverThree = GetUserViewNameByID(moniThreeID) + " " + GetUserNameByID(moniThreeID);

                    }
                }
                //InitDriverComboBoxAddDriver();
                this.cob_opDriver.Text = opDriver;
                this.cob_moniDriver.Text = moniDriver;
                this.cob_moniDriverTwo.Text = moniDriverTwo;
                this.cob_moniDriverThree.Text = moniDriverThree ;

            }

            if (Action == 3)
            {
                if (this.cob_Index.SelectedIndex == -1)
                {
                    return;
                }
                int index = Convert.ToInt32(cob_Index.SelectedValue);
                index = GetIndexByNO(index);
                string opDriver = "";
                string moniDriver = "";
                string moniDriverTwo = "";
                string moniDriverThree = "";
                string sql = "select * from DriverCombine where dcom_team = '" + teamID + "' and dcom_date is null and dcom_dutynum='" + index + "' and dcom_lineid='" + lineid + "'";
                DataTable dt = sqlHelper.SelectDt(sql);
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["dcom_opdriver"].ToString() != "")
                    {
                        int opID = Convert.ToInt32(dt.Rows[0]["dcom_opdriver"].ToString());
                        opDriver = GetUserViewNameByID(opID) + " " + GetUserNameByID(opID);
                    }
                    if (dt.Rows[0]["dcom_monidriver"].ToString() != "")
                    {
                        int moniID = Convert.ToInt32(dt.Rows[0]["dcom_monidriver"].ToString());
                        moniDriver = GetUserViewNameByID(moniID) + " " + GetUserNameByID(moniID);

                    }
                    if (dt.Rows[0]["dcom_monidriverTwo"].ToString() != "")
                    {
                        int moniTwoID = Convert.ToInt32(dt.Rows[0]["dcom_monidriverTwo"].ToString());
                        moniDriverTwo = GetUserViewNameByID(moniTwoID) + " " + GetUserNameByID(moniTwoID);
                    }

                    if (dt.Rows[0]["dcom_monidriverThree"].ToString() != "")
                    {
                        int moniThreeID = Convert.ToInt32(dt.Rows[0]["dcom_monidriverThree"].ToString());
                        moniDriverThree = GetUserViewNameByID(moniThreeID) + " " + GetUserNameByID(moniThreeID);

                    }
                }
                InitDriverComboBoxAddDriver();
                this.cob_opDriver.Text = opDriver;
                this.cob_moniDriver.Text = moniDriver;
                this.cob_moniDriverTwo.Text = moniDriverTwo;
                this.cob_moniDriverThree.Text = moniDriverThree;

                if (!string.IsNullOrEmpty(opDriver))
                    this.cob_opDriver.IsEnabled = false;
                if (!string.IsNullOrEmpty(moniDriver))
                    this.cob_moniDriver.IsEnabled = false;
                if (!string.IsNullOrEmpty(moniDriverTwo))
                    this.cob_moniDriverTwo.IsEnabled = false;
                if (!string.IsNullOrEmpty(moniDriverThree))
                    this.cob_moniDriverThree.IsEnabled = false;
            }
            else
            {
                EnableDrivers();
            }
        }

        private void cob_date_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string sql_Update = "delete from DriverCombine where dcom_date is  null and dcom_lineid='" + lineid + "';SET IDENTITY_INSERT DriverCombine ON;INSERT INTO [DriverCombine]([ID] ,[dcom_lineid],[dcom_team],[dcom_dutynum],[dcom_opdriver],[dcom_monidriver],[dcom_cr_number],[dcom_ybarrive],[dcom_grp_type],[dcom_monidriverTwo],[dcom_NO],[dcom_monidriverThree])select [dcom_parents] ,[dcom_lineid],[dcom_team],[dcom_dutynum],[dcom_opdriver],[dcom_monidriver],[dcom_cr_number],[dcom_ybarrive],[dcom_grp_type],[dcom_monidriverTwo],[dcom_NO],[dcom_monidriverThree] from DriverCombine where dcom_date='" + cob_date.SelectedValue.ToString() + "' and dcom_lineid='" + lineid + "';SET IDENTITY_INSERT DriverCombine OFF";
            sqlHelper.ExecuteSql(sql_Update);
            //RefreshIndexComboBox();
            InitTeamList();
            InitDriverGroupList();

        }

        /// <summary>
        /// 获取可选择的日期
        /// </summary>
        /// <returns></returns>
        public void InitDate()
        {
            string str = " select distinct CONVERT(varchar(100), dcom_date, 23) as dcom_date  from DriverCombine where dcom_date is not null and dcom_date>='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and dcom_lineid='" + lineid + "' order by dcom_date desc";
            DataTable dt = sqlHelper.SelectDt(str);
            cob_date.ItemsSource = dt.DefaultView;
            cob_date.DisplayMemberPath = "dcom_date";
            cob_date.SelectedValuePath = "dcom_date";



        }
        //导入数据
        private void btn_InportDriverCombine_Click(object sender, RoutedEventArgs e)
        {
            btn_InportDriverCombine.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ToImportExcel(ImportExcel));
            tip = new ShowTip();
            tip.ShowDialog();
        }

        public delegate void ToImportExcel();
        public void ImportExcel()
        {
            if (FilePath == "")
            {
                MessageBoxHelper.ShowError("请选择Excel文件");
                return;
            }
            try
            {
                excelHelper = new ExcelHelper(FilePath);
                List<string> sheetName = excelHelper.GetSheetNames();
                Array content = excelHelper.GetContent(sheetName[0]);
                //DataTable dt1 = excelHelper.GetSimpleDataTable(sheetName[0]);
                #region 检查司机是否存在
                string NullName = "";
                const int EXCELLENGTH = 6;
                const int DRIVERCOUNT = 6;
                if (content.Length / EXCELLENGTH <= 3)
                {
                    MessageBoxHelper.ShowError("导入司机表失败,表中数据为空，请确认表中存在司机信息数据！");
                    return;
                }

                for (int i = 4; i <= content.Length / EXCELLENGTH; i++)
                {
                    for (int j = 2; j <= EXCELLENGTH; j++)
                    {
                        //排除备注，序号列
                        if (j % DRIVERCOUNT == 0 || j % DRIVERCOUNT == 1)
                        {
                            continue;
                        }
                        //检查司机是否存在
                        if (((object[,])(content))[i, j] != null)
                        {
                            bool flag = true;
                            foreach (KeyValuePair<int, Driver> kvp in DicDriverInfo)
                            {
                                if (kvp.Value.userViewName == ((object[,])(content))[i, j].ToString().Trim())
                                {
                                    flag = false;
                                    break;
                                }
                            }
                            if (flag)
                            {
                                if (!NullName.Contains(((object[,])(content))[i, j].ToString()))
                                    NullName += ((object[,])(content))[i, j].ToString();

                                NullName += " ";
                            }
                        }

                    }
                }
                #endregion

                if (NullName != "" || NullName.Length > 0)
                {
                    MessageBoxHelper.ShowError("司机：" + NullName + "不存在，请检查是否有该司机！");
                    return;
                }
                int team = -1;
                if (((object[,])(content))[2, 1].ToString() == "电客车一组")
                {
                    team = 1;
                }
                else if (((object[,])(content))[2, 1].ToString() == "电客车二组")
                {
                    team = 2;
                }
                else if (((object[,])(content))[2, 1].ToString() == "电客车三组")
                {
                    team = 3;
                }
                else if (((object[,])(content))[2, 1].ToString() == "电客车四组")
                {
                    team = 4;
                }
                else
                {
                    MessageBoxHelper.ShowError("导入司机表失败，不存在除电客车司机一、二、三、四组外的其他组，请检查表中的数据是否在误！");
                    return;
                }

                ArrayList sqlList = new ArrayList();
                string sql = "delete from DriverCombine where dcom_date is null and dcom_team='" + team + "' and dcom_lineid=" + lineid;
                sqlList.Add(sql);
                #region 把司机信息插入数据库
                int countTeamOne = 0;
                int countTeamTwo = 0;
                int countTeamThr = 0;
                int countTeamFou = 0;

                for (int i = 4; i <= content.Length / EXCELLENGTH; i++)
                {
                    string num = "";
                    string opDriver = "";
                    string minoDriver = "";
                    string minoDriverTwo = "";
                    string minoDriverThree = "";
                    string mono = "";
                    for (int j = 1; j <= EXCELLENGTH; j++)
                    {
                        
                        //获取同一组司机在表中的所有信息
                        num = "";
                        opDriver = "";
                        minoDriver = "";
                        minoDriverTwo = "";
                        minoDriverThree = "";
                        mono = "";
                        if (((object[,])(content))[i, j] != null && ((object[,])(content))[i, j].ToString().Trim()!="")
                            num = ((object[,])(content))[i, j].ToString().Trim();
                        if (((object[,])(content))[i, j + 1] != null && ((object[,])(content))[i, j+1].ToString().Trim() != "")
                            opDriver = Convert.ToString(GetIDByUserViewName(((object[,])(content))[i, j + 1].ToString().Trim()));
                        if (((object[,])(content))[i, j + 2] != null && ((object[,])(content))[i, j+2].ToString().Trim() != "")
                            minoDriver = Convert.ToString(GetIDByUserViewName(((object[,])(content))[i, j + 2].ToString().Trim()));
                        if (((object[,])(content))[i, j + 3] != null && ((object[,])(content))[i, j+3].ToString().Trim() != "")
                            minoDriverTwo = Convert.ToString(GetIDByUserViewName(((object[,])(content))[i, j + 3].ToString().Trim())).Trim();
                        if (((object[,])(content))[i, j + 4] != null && ((object[,])(content))[i, j + 4].ToString().Trim() != "")
                            minoDriverThree = Convert.ToString(GetIDByUserViewName(((object[,])(content))[i, j + 4].ToString().Trim())).Trim();
                        if (((object[,])(content))[i, j + 5] != null )
                            mono = ((object[,])(content))[i, j + 5].ToString().Trim();

                        //该组没有司机信息
                        if (opDriver == "" && minoDriver == "" && minoDriverTwo == "")
                        {
                            continue;
                        }

                        if (mono == "热备")
                        {
                            mono = "1";
                        }
                        else if (mono == "调车")
                        {
                            mono = "2";
                        }
                        else if (mono == "试车线")
                        {
                            mono = "3";
                        }
                        else if (mono == "备班")
                        {
                            mono = "4";
                        }
                        else if (mono == "" || mono == "正线")
                        {
                            mono = "5";
                        }
                        else if (mono == "月备班")
                        {
                            mono = "6";
                        }
                        else if (mono == "司机长")
                        {
                            mono = "7";
                        }
                        else if (mono == "督导员")
                        {
                            mono = "8";
                        }
                        else if (mono == "派班员")
                        {
                            mono = "9";
                        }
                        else
                        {
                            MessageBoxHelper.ShowError("导入司机表失败,备注不能是：" + mono + ",请检查EXCEL表中的内容是否合法！");
                            return;
                        }
                        string strOpDriver = opDriver == "" ? "NULL" : "'" + opDriver + "'";
                        string strMinoDriver = minoDriver == "" ? "NULL" : "'" + minoDriver + "'";
                        string strMinoDriverTwo = minoDriverTwo == "" ? "NULL" : "'" + minoDriverTwo + "'";
                        string strMinoDriverThree = minoDriverThree == "" ? "NULL" : "'" + minoDriverThree + "'";
                        if (team == 1)
                        {
                            countTeamOne++;
                            if (countTeamOne != Convert.ToInt32(num))
                            {
                                MessageBoxHelper.ShowError("导入司机表失败,电客车司机一组序号有误，同一组司机的编号在导入的EXCEL中必须是按顺序排列的！");
                                return;
                            }
                            //if (countTeamOne >= gridList.RowDefinitions.Count - 1)
                            //{
                            //    MessageBoxHelper.ShowError("导入司机表失败,电客车司机一组允许最大组合超出范围，如需扩展，请与工作人员联系！");
                            //    return;
                            //}
                            sql = "insert into DriverCombine (dcom_lineid,dcom_team,dcom_opdriver,dcom_monidriver,dcom_monidriverTwo,dcom_monidriverThree,dcom_grp_type,dcom_dutynum,dcom_no)  values('"
                            + lineid + "','" + team + "'," + strOpDriver + "," + strMinoDriver + "," + strMinoDriverTwo +","+strMinoDriverThree+ ",'" + mono + "','" + countTeamOne + "','" + countTeamOne + "')";
                        }
                        else if (team == 2)
                        {
                            countTeamTwo++;
                            if (countTeamTwo != Convert.ToInt32(num))
                            {
                                MessageBoxHelper.ShowError("导入司机表失败,电客车司机二组序号有误，同一组司机的编号在导入的EXCEL中必须是按顺序排列的！");
                                return;
                            }
                            //if (countTeamTwo >= gridList.RowDefinitions.Count - 1)
                            //{
                            //    MessageBoxHelper.ShowError("导入司机表失败,电客车司机二组允许最大组合超出范围，如需扩展，请与工作人员联系！");
                            //    return;
                            //}
                            sql = "insert into DriverCombine (dcom_lineid,dcom_team,dcom_opdriver,dcom_monidriver,dcom_monidriverTwo,dcom_monidriverThree,dcom_grp_type,dcom_dutynum,dcom_no)  values('"
                            + lineid + "','" + team + "'," + strOpDriver + "," + strMinoDriver + "," + strMinoDriverTwo +","+strMinoDriverThree+ ",'" + mono + "','" + countTeamTwo + "','"+countTeamTwo+"')";
                        }
                        else if (team == 3)
                        {
                            countTeamThr++;
                            if (countTeamThr != Convert.ToInt32(num))
                            {
                                MessageBoxHelper.ShowError("导入司机表失败,电客车司机三组序号有误，同一组司机的编号在导入的EXCEL中必须是按顺序排列的！");
                                return;
                            }
                            //if (countTeamThr >= gridList.RowDefinitions.Count - 1)
                            //{
                            //    MessageBoxHelper.ShowError("导入司机表失败,电客车司机三组允许最大组合超出范围，如需扩展，请与工作人员联系！");
                            //    return;
                            //}

                            sql = "insert into DriverCombine (dcom_lineid,dcom_team,dcom_opdriver,dcom_monidriver,dcom_monidriverTwo,dcom_monidriverThree,dcom_grp_type,dcom_dutynum,dcom_no)  values('"
                            + lineid + "','" + team + "'," + strOpDriver + "," + strMinoDriver + "," + strMinoDriverTwo +","+strMinoDriverThree+ ",'" + mono + "','" + countTeamThr + "','" + countTeamThr + "')";
                        }
                        else if (team == 4)
                        {
                            countTeamFou++;
                            if (countTeamFou != Convert.ToInt32(num))
                            {
                                MessageBoxHelper.ShowError("导入司机表失败,电客车司机四组序号有误，同一组司机的编号在导入的EXCEL中必须是按顺序排列的！");
                                return;
                            }
                            //if (countTeamFou >= gridList.RowDefinitions.Count - 1)
                            //{
                            //    MessageBoxHelper.ShowError("导入司机表失败,电客车司机四组允许最大组合超出范围，如需扩展，请与工作人员联系！");
                            //    return;
                            //}
                            sql = "insert into DriverCombine (dcom_lineid,dcom_team,dcom_opdriver,dcom_monidriver,dcom_monidriverTwo,dcom_monidriverThree,dcom_grp_type,dcom_dutynum,dcom_no)  values('"
                            + lineid + "','" + team + "'," + strOpDriver + "," + strMinoDriver + "," + strMinoDriverTwo +","+strMinoDriverThree+ ",'" + mono + "','" + countTeamFou + "','" + countTeamFou + "')";
                        }
                        sqlList.Add(sql);
                        j += 5;
                    }
                   
                }
                #endregion

                if (sqlHelper.ExecuteSqlTran(sqlList))
                {
                    this.btn_InportDriverCombine.IsEnabled = false;
                    this.tb_Path.Text = "";
                    FilePath = "";

                    MessageBoxHelper.ShowTips("导入司机表成功!");
                    InitTeamList();
                    InitDriverGroupList();
                }
                else
                {
                    MessageBoxHelper.ShowError("导入司机表失败");
                }

            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError("导入司机表失败，请检查表数据是否有错误！");
            }
            finally
            {
                tip.Visibility = Visibility.Collapsed;
                tip.Close();
                if (excelHelper != null)
                {
                    excelHelper.Close();
                }
            }
        }
        private string FilePath = "";
        private void btn_InportDriverSelect_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".xls;xlsx";
            dlg.Filter = "Excel Files (.xls,*.xlsx)|*.xls;*.xlsx";
            dlg.RestoreDirectory = true;
            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process open file dialog box results 
            if (result == true)
            {
                FilePath = dlg.FileName;
                this.tb_Path.Text = FilePath;
                this.btn_InportDriverCombine.IsEnabled = true;
            }
        }

        private void SaveSetting_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (cob_date.SelectedValue==null)
                {
                    MessageBoxHelper.ShowTips("请选择日期！");
                    return;
                }
                string sql_Update = "delete from DriverCombineTemp;SET IDENTITY_INSERT DriverCombineTemp ON;INSERT INTO [DriverCombineTemp]([ID] ,[dcom_lineid],[dcom_team],[dcom_dutynum],[dcom_opdriver],[dcom_monidriver],[dcom_cr_number],[dcom_ybarrive],[dcom_grp_type],[dcom_monidriverTwo],dcom_date,[dcom_NO],[dcom_monidriverThree])select [ID] ,[dcom_lineid],[dcom_team],[dcom_dutynum],[dcom_opdriver],[dcom_monidriver],[dcom_cr_number],[dcom_ybarrive],[dcom_grp_type],[dcom_monidriverTwo],'" + cob_date.SelectedValue.ToString() + "',[dcom_NO],[dcom_monidriverThree] from DriverCombine where dcom_date is null and dcom_lineid='" + lineid + "';SET IDENTITY_INSERT DriverCombineTemp OFF";
            
                if (sqlHelper.ExecuteSql(sql_Update) > 0)
                {
                    MessageBoxHelper.ShowTips("更新数据成功");
                }
            }
            catch (Exception ex)
            {

                MessageBoxHelper.ShowError(ex);
            }
          
        }

        private void LoadData_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string sql_Update = "delete from DriverCombine where dcom_date is  null;SET IDENTITY_INSERT DriverCombine ON;INSERT INTO [DriverCombine]([ID] ,[dcom_lineid],[dcom_team],[dcom_dutynum],[dcom_opdriver],[dcom_monidriver],[dcom_cr_number],[dcom_ybarrive],[dcom_grp_type],[dcom_monidriverTwo],[dcom_NO],[dcom_monidriverThree]) select [ID] ,[dcom_lineid],[dcom_team],[dcom_dutynum],[dcom_opdriver],[dcom_monidriver],[dcom_cr_number],[dcom_ybarrive],[dcom_grp_type],[dcom_monidriverTwo],[dcom_NO],[dcom_monidriverThree] from DriverCombineTemp;SET IDENTITY_INSERT DriverCombine OFF";
                sqlHelper.ExecuteSql(sql_Update);
                //RefreshIndexComboBox();
                InitTeamList();
                InitDriverGroupList();
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex);
            }
        
        }

    }

    public class Driver
    {
        public string userid { get; set; }
        public string userName { get; set; }
        public string userViewName { get; set; }
        public string userViewNameAndUserName { get; set; }
        public int group { get; set; }
    }

    /// <summary>
    /// 检查某司机是否存在某分组时使用
    /// </summary>
    class DriverIn
    {
        public int _userId;
        public string userName;
        public int _team;
        public int _index;
        public string _type;
        public string _opDriver;
        public string _monDriver;
        public string _monDriverTwo;
        public string _monDriverThree;
        public int _dcomNO;


        public DriverIn() { ;}
        public DriverIn(int userid, int team, int index, string type, string op, string mon, string monTwo,string monThree,int no)
        {
            this._userId = userid;
            this._team = team;
            this._index = index;
            this._type = type;
            this._opDriver = op;
            this._monDriver = mon;
            this._monDriverTwo = monTwo;
            this._monDriverThree = monThree;
            this._dcomNO = no;
        }
        public DriverIn(int userid, int team, int index, string type, string op, string mon, string monTwo,string monThree)
        {
            this._userId = userid;
            this._team = team;
            this._index = index;
            this._type = type;
            this._opDriver = op;
            this._monDriver = mon;
            this._monDriverTwo = monTwo;
            this._monDriverThree = monThree;
        }

    }


    public class DriverGroupCombine : DockPanel
    {
        private static TextBlock currentHightlight;
        private Brush highlightBrush = Brushes.Blue;
        private Brush highlightBackgroundBrush = Brushes.Red;
        private Brush normalBrush = Brushes.Black;
        private Brush normalBackgroundBrush = Brushes.Green;


        public void setHighlight(int loc)
        {
            if (currentHightlight != null)
            {
                currentHightlight.Foreground = normalBrush;
                //currentHightlight.Background = normalBackgroundBrush;
                ((DriverGroupCombine)currentHightlight.Parent).Background = normalBackgroundBrush;
            }

            switch (loc) {
                case 0:
                    currentHightlight = tbkOperateDriver;
                    break;
                case 1:
                    currentHightlight = tbkMonitorDriver;
                    break;
                case 2:
                    currentHightlight = tbkMonitorDriverTwo;
                    break;
                case 3:
                    currentHightlight = tbkMonitorDriverThree;
                    break;
                default:
                    return;
            }
            currentHightlight.Foreground = highlightBrush;
            ((DriverGroupCombine)currentHightlight.Parent).Background = highlightBackgroundBrush;
        }
        private TextBox tbIndex;
        private TextBlock tbkOperateDriver;
        private TextBlock tbkMonitorDriver;
        private TextBlock tbkMonitorDriverTwo;
        private TextBlock tbkMonitorDriverThree;
        private TextBlock tbkNotes;

        //private SqlDataLayer sqlHelper = new SqlDataLayer();
        private ContextMenu contextMenu;

        public string ID { get; set; }

        public int Team { get; set; }

        private int Type { get; set; }

        public string Index
        {
            get { return this.tbIndex.Text; }
            set
            {
                this.tbIndex.Text = value;
            }
        }

        public string OperateDriver
        {
            get { return this.tbkOperateDriver.Text; }
            set
            {
                this.tbkOperateDriver.Text = value;
            }
        }

        public string MonitorDriver
        {
            get { return this.tbkMonitorDriver.Text; }
            set
            {
                this.tbkMonitorDriver.Text = value;
            }
        }

        public string MonitorDriverTwo
        {
            get { return this.tbkMonitorDriverTwo.Text; }
            set
            {
                this.tbkMonitorDriverTwo.Text = value;
            }
        }

        public string MonitorDriverThree
        {
            get { return this.tbkMonitorDriverThree.Text; }
            set
            {
                this.tbkMonitorDriverThree.Text = value;
            }
        }
        public string Notes
        {
            get { return this.tbkNotes.Text; }
            set
            {
                this.tbkNotes.Text = value;

                Type = GetTypeByName(value);
            }
        }


        public DriverGroupCombine(int index)
        {

            //this.tbkIndex = GetTextBlock(20);
            this.tbIndex = GetIndexTextBox();
            this.tbkOperateDriver = GetTextBlock(67);
            this.tbkMonitorDriver = GetTextBlock(67);
            this.tbkMonitorDriverTwo = GetTextBlock(67);
            this.tbkMonitorDriverThree = GetTextBlock(67);

            this.tbkNotes = GetTextBlock(50);

            this.Index = index.ToString();

            this.Children.Add(tbIndex);
            this.Children.Add(tbkOperateDriver);
            this.Children.Add(tbkMonitorDriver);
            this.Children.Add(tbkMonitorDriverTwo);
            this.Children.Add((tbkMonitorDriverThree));
            this.Children.Add(tbkNotes);

            InitContextMeum();

            this.Background = Brushes.GreenYellow;
        }

        public void InitContextMeum()
        {
            if (null == contextMenu)
            {
                contextMenu = new ContextMenu();
            }

            MenuItem item1 = new MenuItem();
            item1.Header = "热备";
            item1.Click += new RoutedEventHandler(MenuItem_Click);

            MenuItem item2 = new MenuItem();
            item2.Header = "调车";
            item2.Click += new RoutedEventHandler(MenuItem_Click);

            MenuItem item3 = new MenuItem();
            item3.Header = "试车线";
            item3.Click += new RoutedEventHandler(MenuItem_Click);

            MenuItem item4 = new MenuItem();
            item4.Header = "备班";
            item4.Click += new RoutedEventHandler(MenuItem_Click);

            MenuItem item5 = new MenuItem();
            item5.Header = "正线";
            item5.Click += new RoutedEventHandler(MenuItem_Click);

            MenuItem item6 = new MenuItem();
            item6.Header = "月备班";
            item6.Click += new RoutedEventHandler(MenuItem_Click);

            MenuItem item7 = new MenuItem();
            item7.Header = "司机长";
            item7.Click += new RoutedEventHandler(MenuItem_Click);

            MenuItem item8 = new MenuItem();
            item8.Header = "督导员";
            item8.Click += new RoutedEventHandler(MenuItem_Click);

            MenuItem item9 = new MenuItem();
            item9.Header = "派班员";
            item9.Click += new RoutedEventHandler(MenuItem_Click);

            contextMenu.Items.Add(item7);
            contextMenu.Items.Add(item5);
            contextMenu.Items.Add(item1);
            contextMenu.Items.Add(item2);
            contextMenu.Items.Add(item3);
            contextMenu.Items.Add(item4);
            contextMenu.Items.Add(item6);
            contextMenu.Items.Add(item8);
            contextMenu.Items.Add(item9);

            this.ContextMenu = contextMenu;
        }

        void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem item = sender as MenuItem;
            if (null == item)
                return;

            SetSpecialGroup(item.Header.ToString());
        }

        //public int GetIndexByNO(int index)
        //{
        //    string strSqlNO = "select dcom_dutynum from DriverCombine where dcom_NO = '" + index + "' and dcom_date is null and dcom_team='" + Team + "' and dcom_lineid='" + DriverCombineView.lineid + "'";
        //    DataTable dt = sqlHelper.SelectDt(strSqlNO);
        //    if (dt.Rows.Count > 0)
        //    {
        //        return Convert.ToInt32(dt.Rows[0]["dcom_dutynum"].ToString());
        //    }
        //    else
        //    {
        //        return -1;
        //    }
        //}

        private void SetSpecialGroup(string header)
        {
            if (header == "正线")
                header = "";

            int typeID = GetTypeByName(header);

            if (typeID == -1)
            {
                MessageBoxHelper.ShowError("无法识别所选分组，更新失败！");
            }
            if (typeID == Type)  //如果相同则不更新
                return;

            string sql_updateType = "update DriverCombine set dcom_grp_type = " + typeID + " where dcom_lineid = " + DriverCombineView.lineid + " and dcom_team = '" + Team + "' and dcom_no = '" + Index + "' and dcom_date is null";
            SqlDataLayer sqlHelper = new SqlDataLayer();
            if (sqlHelper.ExecuteSql(sql_updateType) > 0)
            {
                MessageBoxHelper.ShowTips("更新成功！");
                this.tbkNotes.Text = header;
                Type = typeID;
            }
            else
                MessageBoxHelper.ShowError("更新失败！");
        }

        private int GetTypeByName(string name)
        {
            int typeID = -1;

            DriverCombineView.Group.TryGetValue(name, out typeID);


            return typeID;
        }

        public void InitColor()
        {
            if (this.Background != Brushes.GreenYellow)
            {
                this.Background = Brushes.GreenYellow;
            }
        }

        public void ReInit()
        {
            this.ID = "";
            this.Index = "";
            this.OperateDriver = "";
            this.MonitorDriver = "";
            this.MonitorDriverTwo = "";
            this.Notes = "";
            this.Background = Brushes.White;
        }

        private TextBox GetIndexTextBox()
        {
            TextBox tb = new TextBox();
            tb.BorderBrush = Brushes.Transparent;
            tb.Background = Brushes.Transparent;
            tb.IsReadOnly = true;
            tb.MaxLength = 2;
            tb.Margin = new Thickness(10, 0, 0, 0);
            tb.Width = 30;
            tb.VerticalAlignment = VerticalAlignment.Center;
            tb.FontSize = 16;
            tb.PreviewKeyDown += new KeyEventHandler(tb_PreviewKeyDown);
            tb.PreviewTextInput += new TextCompositionEventHandler(tb_PreviewTextInput);
            return tb;
        }

        public void SetTbEditable(bool state)
        {
            this.tbIndex.IsReadOnly = !state;
            if (state)
                this.tbIndex.Background = Brushes.LightYellow;
            else
                this.tbIndex.Background = Brushes.Transparent;
        }

        void tb_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!GlobalVariables.IsNumberic(e.Text))
            {
                e.Handled = true;
            }
            else
                e.Handled = false;
        }

        void tb_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space)
                e.Handled = true;
        }

        private TextBlock GetTextBlock(double width)
        {
            TextBlock tbk = new TextBlock();
            tbk.Margin = new Thickness(10, 0, 0, 0);
            tbk.Width = width;
            tbk.VerticalAlignment = VerticalAlignment.Center;
            tbk.FontSize = 16;
            return tbk;
        }





    }
}
